how 2d object move to a position???

I am a beginner of coding, I want the object “player” move to (7,0) from (-7,0). and I have no idea how to do it, pls help me!!!
I tried some by myself, the object “player” only move to the middle and stop. here is the code I made.

public class battleRule : MonoBehaviour
{

    public GameObject player;
    public GameObject enemy;
    float playerSpeed = 10;
    float enemySpeed = 5;

    // Start is called before the first frame update
    void Start()
    {
        player.transform.position = Vector2.MoveTowards(transform.position, new Vector2(7, 0), Time.deltaTime * 1);
    }

    // Update is called once per frame
    void Update()
    {
        attack();


    }

    void attack()
    {
        if (playerSpeed > enemySpeed)
        {
            player.transform.position = Vector2.MoveTowards(transform.position, new Vector2(20, 0), Time.deltaTime * 1);
        }
    }




}

Do you want your character to move between two points continuously? i mean -7 to 7 to -7 to 7 ?

2 Answers

2

if you want to move the player, your MoveToward() method’s first input should probably be player.transform.position instead of transform.position. transform.position gives you the position of the gameObject your script (in this case ‘battleRule’) is currently attached to.

Change this:

player.transform.position = Vector2.MoveTowards(transform.position, …

To this:

player.transform.position = Vector2.MoveTowards(player.transform.position, …

And remove it from Start and put it inside Update. MoveTowards happens during a period of time, if you don’t put it inside a “loop” function it will only run 1 frame.

Also, comment the attack(); function being called inside Update.

Here is a move towards explanation