Scripting problems in Unity - c#

I'm a Unity beginner.
I have a problem with my script: in the picture above, Player item does not exist in Move script.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed;
public Transform player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
transform.Translate(x * speed * Time.deltaTime, y * speed * Time.deltaTime, 0);
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - player.position;
player.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
}
}

I am not sure if I understand you right, but as this script is the script that belongs to the Player Gameobject, you don't need to specify "public Transform player".
The Gameobject class inherits from the Transform class, so it should work if you try:
Vector2 v2 = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(v2.y, v2.x) * Mathf.Red2Deg);
Maybe to make it more clear:
You don't need to have Player as an "item" that you pull into the according field in the inspector as it was the case if you relate to a gameobject which does not contain the "Move" script.
So, if you attach a script to a gameobject (in this case you attach the script to "Player"), then any methods you script, are directly affecting the gameobject the script belongs to.
E.g. try the following:
void Update() {
if(Input.GetKeyDown("space")) {
Destroy(gameObject);
}
}
You will see that the circle, which forms your player, will destroy itself when you hit the space bar. The parameter "gameObject" refers to the gameobject the script belongs to.
I hope that helps you to understand that you don't need to specify an extra GameObject that needs to be linked to the script, as long as the Gameobject you want to manipulate contains this script.

Related

How can I share data from onTriggerEnter method to smoothly move the position of a game object, using Update method?

enter image description hereI am able to set Y axis of my player with a simple transform.position call, in a single step, all within onTriggerEnter method, but the motion has a single step and is therefore jerky. Now I am trying to make the motion smooth by putting the transform.position function in an Update method within the same class. However, it seems that the position values determined/updated by onTriggerEnter method are not accessible in the Update function. If I print the x and z values to console, they contain expected values from onTriggerEnter function, but appear to be 0 when I print to console from the update function.
Any ideas of what I am doing wrong?
I would never call myself a programmer, so assume the worst :-)
Thanks in advance for any help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Step1SetElevation : MonoBehaviour
{
private float moveSpeed = 3f;
private float currX = 0.0f;
private float currZ = 0.0f;
private Vector3 currentPos;
private GameObject player;
private Collider other;
void OnTriggerEnter(Collider other)
{
player = GameObject.FindWithTag("Player");
currentPos = GameObject.Find("PlayerController").transform.position;
currX = currentPos.x;
currZ = currentPos.z;
}
void Update()
{
player = GameObject.FindWithTag("Player");
player.transform.position = new Vector3(currX, 3.4f, currZ) * Time.deltaTime * moveSpeed;
}
}
I believe your problem may be that you are using OnTriggerEnter() to set the position you want your player to move to, this will be called on the frame your player enters your trigger but then won't be called again until the player left and re-entered...
If you instead use OnTriggerStay() - something like
void Start(){ // this lookup can be expensive so lets only do it once
player = GameObject.FindWithTag("Player");
playerController = GameObject.Find("PlayerController");
}
void OnTriggerStay(Collider other){ // this is called once per frame that a collider remains in a trigger
if(other.gameObject.tag == "Player"){ // just in case anything else ever enters the collider
currentPos = playerController.transform.position;
currX = currentPos.x;
currZ = currentPos.z;
}
}
void FixedUpdate(){ // it's generally advised to move objects in fixed update
player.transform.position = new Vector3(currX, 3.4f, currZ) * Time.fixedDeltaTime * moveSpeed;
}

I want my object to fall when the player is near it

I want my objects to fall when the player got to that scene . My game have a long map and I want them not to fall when I start the game .There is any code for player detection in the view? for the objects to fall?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FallDown : MonoBehaviour
{
public float fallSpeed = 8.0f;
//Variables for starting position and length until reset
private Vector3 _startingPos;
public float FallDistance = 5f;
void Start()
{
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
// Save starting position
_startingPos = transform.position;
}
void Update()
{
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
// If the object has fallen longer than
// Starting height + FallDistance from its start position
if (transform.position.y > _startingPos.y + FallDistance)
{
transform.position = _startingPos;
}
}
}
While the answer above is correct, Colliders might not be what you want to implement in this case. Colliders are used to, well, detect collisions, while you want the objects to fall when the player is at a specific distance from them. For this, I'd suggest adding a reference to the player GameObject first:
private GameObject playerRef;
And in the Start function find the player:
playerRef = GameObject.Find("yourPlayerGameObjectNameHere");
Get the GameObjects that you want to fall either by finding them, like above, or by passing a public reference to them through the inspector. Afterwards, you can use Vector3.distance between each GameObject and the player, like so:
if( Vector3.Distance(player.transform.position, fallingObject.transform.position) < yourDistanceHere ){
// Make the object fall
}
Have you tried implementing this behavior using Colliders?
To do it so, all you've got to do is add both a Collider Component and a RigidBody to your player and to the falling objects.
Once you've added them and configured their parameters, you can check the collision by using the method OnColissionEnter. This method will be triggered every time that a collision is detected by the GameObject that is holding the script. In your case, the falling objects should hold it.
private void OnCollisionEnter(Collision other)
{
//MAKE THE OBJECTS FALL
}

Movement Script In Unity C#

I have been trying to make a movement script for my player in a 2D game but without success. I do not know why it is not working.
The problem is that the player isn't moving. I have a RigidBody attached and gravity on. (Not sure if gravity makes such a difference but I just thought to mention it.)
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float speed = 10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float mx = Input.GetAxisRaw("Horizontal");
float mz = Input.GetAxisRaw("Vertical");
Vector3 movement = new Vector3(mx, 0.0f, mz);
Debug.Log(movement);
rb.AddForce(movement * speed * Time.deltaTime);
}
}
You may wanna make sure you are adding enough force to actually cause the player to move. Try increasing the force variable incrementally until you see a change. Hope this helps!

Unity2D - Companion

When reading this, keep in mind I'm new to both programming and Unity, so I might be missing some terms or tools Unity offer. Please elaborate your answers in an ELI5 manner. Thanks in advance!
I am currently working on some game-physics for a small personal project. Currently I've created a platform, a character and what should be, a following companion.
However, since I'm still not on a level, where I can create perfect code on own hand, I found an "enemy" script and tried to modify it a bit.
It Works to an extend, but it needs some tweaks which I hope I can help aquire with you guys.
This is how it looks now (the orange square is the companion)
It follows the player, and I can tweak the speed to fit as a companion, and not a player. However, as the Picture presents, the companion runs for the center of the player. What I want to create is a companion which follows the player, but still keeps a small gap from the player.
My first thoughts was to create some kind of permanent offset, but I fail to figure out how to do this without messing up the follow function.
I hope you can help me, it will be much appreciated!
Here's the code for reference.
Code attached to Player:
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
//In the editor, add your wayPoint gameobject to the script.
public GameObject wayPoint;
//This is how often your waypoint's position will update to the player's position
private float timer = 0.5f;
void Update ()
{
if (timer > 0) {
timer -= Time.deltaTime;
}
if (timer <= 0) {
//The position of the waypoint will update to the player's position
UpdatePosition ();
timer = 0.5f;
}
}
void UpdatePosition ()
{
//The wayPoint's position will now be the player's current position.
wayPoint.transform.position = transform.position;
}
}
Code attached to companion:
using UnityEngine;
using System.Collections;
public class FollowerOffset : MonoBehaviour {
//You may consider adding a rigid body to the zombie for accurate physics simulation
private GameObject wayPoint;
private Vector3 wayPointPos;
//This will be the zombie's speed. Adjust as necessary.
private float speed = 10.0f;
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
}
void Update ()
{
wayPointPos = new Vector3(wayPoint.transform.position.x, transform.position.y, wayPoint.transform.position.z);
//Here, the zombie's will follow the waypoint.
transform.position = Vector3.MoveTowards(transform.position, wayPointPos, speed * Time.deltaTime);
}
}
bump, I guess ? :)
You can use smooth follow script. I have created a sample class for you. This class has features to follow any given gameobject with some delay and offset. You will have to tweak some values according to your need.
using UnityEngine;
using System.Collections;
public class PlayerCompanion : MonoBehaviour
{
[SerializeField]
private GameObject wayPoint;
[SerializeField]
public Vector3 offset;
public Vector3 targetPos;//Edit: I forgot to declare this on firt time
public float interpVelocity;
public float cameraLerpTime = .1f;
public float followStrength = 15f;
// Use this for initialization
void Start ()
{
//At the start of the game, the zombies will find the gameobject called wayPoint.
wayPoint = GameObject.Find("wayPoint");
offset = new Vector3 (5,0,0);//input amount of offset you need
}
void FixedUpdate () {
if (wayPoint) {
Vector3 posNoZ = transform.position;
Vector3 targetDirection = (wayPoint.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * followStrength;
targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);
transform.position = Vector3.Lerp (transform.position, targetPos + offset, cameraLerpTime);
}
}
}
Attach this class to your player companion, play with different values.
To preserve object orientation your companion schould not be anyways child of your main character.
Your wayPoint doesn't needs to be a GameObject but a Transform instead and your code will looks like better.
If your game is a 2D platform your and your companion needs to be backwards your player it probabli applys to just one axis (X?) so you can decrement your waiPoint in a more directly way by calculating it on your UpdatePosition function like this:
wayPoint.position = transform.position * (Vector3.left * distance);
where your "distance" could be a public float to easily setup.
so on your companion script Update just do:
transform.position = Vector3.MoveTowards(transform.position, wayPoint.position, speed * Time.deltaTime);
I can't test it right now so you could have problems with Vector3 multiply operations, just comment and I'll try to fix as possible ;)

unity 2D player movement parameters do not exist

I've managed to make a little top down shooter now I'm going over animations. I have followed a couple tutorials by pixelnest.io but strangly I'm getting an error saying "parameter 'moveRight' does not exist. animation in unity is completely new to me and have been trying to read up as much as I can. any suggestions to fix the animation so it plays when I move right? below are some pictures and my code.
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour {
public float maxSpeed = 5f;
Animator animator;
bool isRight;
void Awake(){
animator = GetComponent<Animator>();
}
void Update(){
Vector3 posMove = transform.position;
Vector3 velocityH = new Vector3 (Input.GetAxis ("Horizontal") * maxSpeed * Time.deltaTime, 0, 0);
//this is just test a before i add it to the right movement
animator.SetBool ("moveRight", isRight);
Vector3 velocityV = new Vector3 (0, Input.GetAxis ("Vertical") * maxSpeed * Time.deltaTime, 0);
posMove += velocityH + velocityV;
transform.position = posMove;
}
}
This is because you don't have a boolean called "moveRight" in your animator.
Look at the first screenshot you posted. In the bottom left corner, you've declared a single boolean named "isRight".
While using Animator.SetBool(yourBool, boolValue), you first parameter you need to pass is the name of the boolean declared in the animator (in this case, it's "isRight").
Change the following line of code in your script
Change this line
animator.SetBool ("moveRight", isRight);
to read
animator.SetBool ("isRight", isRight);

Categories