Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

MoveTowarrds not working, vector2

Discussion in 'Scripting' started by PachiGG, Jul 7, 2018.

  1. PachiGG

    PachiGG

    Joined:
    Apr 1, 2017
    Posts:
    239
    hi, i am trying to move from to with velocity but the object its just falling and not moving right and i cant find the error, the script is on c#



    Code (CSharp):
    1.  
    2.    
    3.     // Use this for initialization
    4.     private Rigidbody2D rb;
    5.  
    6.     public float speed;
    7.  
    8.     private void Start()
    9.     {
    10.         rb = GetComponent<Rigidbody2D>();
    11.     }
    12.  
    13.     private void FixedUpdate()
    14.     {
    15.         if (Input.GetButtonDown("Fire1"))
    16.         {
    17.             var posicon = Input.mousePosition;
    18.             float step = speed * Time.deltaTime;
    19.  
    20.             Vector2 pz = Camera.main.ScreenToWorldPoint(posicon);
    21.  
    22.             transform.position = Vector2.MoveTowards(transform.position, pz, step);
    23.         }
    24.     }
    25.  
    but its teleporting like no linear velocity
     
    Last edited: Jul 7, 2018
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You're not really using the rigidbody. You're modifying the transform directly.

    Here are a couple of thoughts for your issue:
    1) modifying the transform directly: keep the 'destination' in a variable. Update this variable when you get the ButtonDown. However, use the MoveTowards line of code outside of that if statement, so it's always moving frame after frame.
    2) using the rigidbody, instead. Get the direction to the new position. Normalize that, and then apply your speed. Set the rb's velocity to that.
    Note: this won't stop when you reach the destination, so if that doesn't matter you're good, otherwise you have to check the distance.

    Hope that helps. :)