I’m new to unity and to C# scripting, and I’m trying to improve in the roll-a-ball project. What I wanted to do is to change the camera using the horizontal inputs and accelerate the ball in the chosen direction using the vertical inputs. To do so, I created an empty GameObject and attached the following script to it.
public GameObject player;
public GameObject target;
public float speed;
public float tspeed;
private Rigidbody rb;
void Start ()
{
rb = player.GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float move = Input.GetAxis (“Vertical”);
float turn = Input.GetAxis (“Horizontal”);
rb.AddForce (Vector3.MoveTowards (transform.position, target.transform.position, 1.0f) * move * speed);
transform.Rotate (Vector3.up, turn * tspeed);
}
void LateUpdate ()
{
transform.position = player.transform.position;
}
“player” is the ball and “target” is an empty child to the empty GameObject, positioned (0,0,1) to it. The camera is also a child to the empty GameObject.
Right now, I can easily turn the empty GameObject, along with the camera and the target using the horizontal inputs, and when I press the vertical inputs the ball accelerates in that direction. However, once it starts moving, I can’t change the direction of the aplied force, and it keeps accelerating into infinity (though I can turn the camera and the target). How can I fix this?
Any help is appreciated, and if there’s a way to simplify or make my script better, I’d like to learn it.