I made a little script that should take a coordinates an the move object to it.
But is moves object to an opposite direction.
I am workin with 2d scene.
Here is the code:
public Camera MainCamera; public LayerMask layers; public float movementSpeed = 20.0f; private bool IsMoving = false; private Vector3 targetPosition;
// Use this for initialization
void Start()
{
targetPosition = transform.position;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(1))
{
SetCoordinates();
}
if (IsMoving)
{
Moving();
}
}
private void SetCoordinates()
{
Ray ray = MainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layers))
{
targetPosition.x = hit.point.x;
targetPosition.y = hit.point.y;
targetPosition.z = transform.position.z;
Debug.DrawRay(transform.position, targetPosition, Color.red);
}
IsMoving = true;
}
private void Moving()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementSpeed * Time.deltaTime);
if (transform.position == targetPosition)
{
Debug.Log(targetPosition);
Debug.Log(Input.mousePosition + " mouse pos");
IsMoving = false;
}
}
}