Search Unity

Point A to Point B not moving

Discussion in 'Scripting' started by ZeitGret, Aug 20, 2019.

  1. ZeitGret

    ZeitGret

    Joined:
    Sep 4, 2016
    Posts:
    3
    Hi Guys. Sorry if my coding aren't good. I am having a abit of a problem with one of my codes. So I am trying to get a enemy to move from Point A to Point B. this is 2d based

    Point A and Point B are empty gameobjects with rigidbody2d. But currently the code is only set to have them walk to either point A/B.

    Currently I have a few problems.

    This first code doesn't work the enemy will only stand at their currently location.
    position = Vector2.MoveTowards(position, positionwp1, Time.deltaTime * speed);

    rrigidbody2D.MovePosition(position);

    this is another code the enemy moves but it only move at 1 direction up. If I set it to positionwp2. it still goes up even after I change the position of Point A it still moves up. I am guess its due to the ".y"?

    //position.y = positionwp1.y + Time.deltaTime * speed;

    also the "If(position != Positionwp1)" doesn't seems to work the enemy will just stay at the same location.

    can anyone help?





    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RobotTest : MonoBehaviour
    6. {
    7.     Rigidbody2D rrigidbody2D;
    8.     public float speed = 1.0f;
    9.  
    10.  
    11.     Animator animator;
    12.     public Rigidbody2D wp1;
    13.     public Rigidbody2D wp2;
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         rrigidbody2D = GetComponent<Rigidbody2D>();
    19.         animator = GetComponent<Animator>();
    20.         wp1 = GetComponent<Rigidbody2D>();
    21.         wp2 = GetComponent<Rigidbody2D>();
    22.  
    23.  
    24.     }
    25.  
    26.     // Update is called once per frame
    27.     void Update()
    28.     {
    29.  
    30.         Vector2 position = rrigidbody2D.position;
    31.         Vector2 positionwp1 = wp1.position;
    32.         Vector2 positionwp2 = wp2.position;
    33. if(position != positionwp1)
    34. {
    35.           animator.SetFloat("Move X", 0);
    36.           animator.SetFloat("Move Y", 1);
    37.        // position.y = positionwp2.y + Time.deltaTime * speed;
    38.           position = Vector2.MoveTowards(position, positionwp1, Time.deltaTime * speed);
    39. }
    40.          rrigidbody2D.MovePosition(position);
    41.  
    42.   }
    43.  
    44.  
    45.  
    46. }
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Do you know what wp2 and wp1 is the same rigidbody at same position?
     
  3. ZeitGret

    ZeitGret

    Joined:
    Sep 4, 2016
    Posts:
    3
    Ah. forgotten those weren't on the enemy gameobject. Thanks