Search code examples
c#unity-game-engine2d

MoveTowards doesn't reach to clickpoint


I'd like to move my player object to click point
with constant velocity so I used MoveTowards() method but it teleports towards click point and doesn't reach the point..If it works properly I'll put walking motion in it. Please check my codes..

And I want to get advice on whether use Update() or FixedUpdate(). FixedUpdate() also doesn't wolks well. It takes mouse events not every time.

here's codes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using System.Collections;

namespace Assets.Scripts
{
    public class moveToTarget : MonoBehaviour
    {
        public GameObject player;

        private void Awake()
        {
            player = GameObject.Find("player");
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 clickPoint = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                Input.mousePosition.y, -Camera.main.transform.position.z));

                Vector3 pos = player.transform.position;

                Vector3 current = pos;

                Vector3 desPos = new Vector3(clickPoint.x, pos.y, 0);
                //I want to move object horizontally

                Debug.Log(clickPoint);

                player.transform.position = Vector3.MoveTowards(current, desPos, 100.0f * Time.deltaTime);
            }
        }
    }
}

Solution

  • The Third input of the MoveTowards function is maxDeltaDistance. The bigger it is the faster your object will move. You are using move towards inside an If statement, which might be the cause for not reaching the target.