Search Unity

Trying to aply a force on a rolling ball based on an empty GameObject’s axis

Discussion in 'Getting Started' started by jeandepain, Aug 31, 2018.

  1. jeandepain

    jeandepain

    Joined:
    Aug 31, 2018
    Posts:
    3
    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.

    Code (CSharp):
    1. public GameObject player;
    2. public GameObject target;
    3. public float speed;
    4. public float tspeed;
    5. private Rigidbody rb;
    6.  
    7. void Start ()
    8. {
    9. rb = player.GetComponent<Rigidbody>();
    10. }
    11.  
    12. void FixedUpdate ()
    13. {
    14. float move = Input.GetAxis (“Vertical”);
    15. float turn = Input.GetAxis (“Horizontal”);
    16.  
    17. rb.AddForce (Vector3.MoveTowards (transform.position, target.transform.position, 1.0f) * move * speed);
    18. transform.Rotate (Vector3.up, turn * tspeed);
    19. }
    20.  
    21. void LateUpdate ()
    22. {
    23. transform.position = player.transform.position;
    24. }
    “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 move 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.
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I think you've misunderstood what Vector3.MoveTowards does. The way you're using it, it takes your current position, and computes a point 1 unit closer to the target position... and then you use this position as a force to apply to your ball, which is obviously not valid.

    I think what you're looking for is something more like this:

    Code (csharp):
    1.  
    2. Vector3 towardsBall = target.transform.position - transform.position;
    3. rb.AddForce(towardsBall.normalized * move * speed);
    4.  
     
    jeandepain likes this.
  3. jeandepain

    jeandepain

    Joined:
    Aug 31, 2018
    Posts:
    3
    Thanks! Just tested it and it worked perfectly.