- Home /
MoveTowards is moveing my object to random position when i click it is already on a way
Hello, i want to rotate and after it move my 2D object to clicked position. I used RotateTowards for rotate and MoveTowards for move my object. But sometimes when i click to any position when it is already on a way to position, it is going to random position, not to that first clicked position or second one. I can't understand why sometimes doing this. Also i am open to another ideas about make better my codes because this is my first Unity script. I am not experienced about that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private float movementSpeed = 2;
private float rotationSpeed = 300;
private bool IsRotating = false;
private bool rotated = false;
private bool IsMoving = false;
private Vector3 targetPosition;
private Quaternion rotation;
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log("Tiklandi.");
IsRotating = false;
rotated = false;
IsMoving = false;
SetAngle();
}
if(IsRotating == true && IsMoving == false && rotated == false)
{
Rotation();
}
if (rotated == true && IsRotating == false && IsMoving == false)
{
SetTargetPosition();
}
if (IsMoving == true && rotated == true && IsRotating == false)
{
Move();
}
}
void SetAngle()
{
Debug.Log("SetAngle calisti.");
Vector2 dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
IsRotating = true;
}
void Rotation()
{
Debug.Log("Rotation calisti.");
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
if (transform.rotation == rotation)
{
IsRotating = false;
rotated = true;
}
}
void SetTargetPosition()
{
Debug.Log("SetTargetPosition calisti.");
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = transform.position.z;
Debug.Log(targetPosition);
IsMoving = true;
}
void Move()
{
Debug.Log("Move calisti.");
transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementSpeed * Time.deltaTime);
if (transform.position == targetPosition)
{
rotated = false;
IsMoving = false;
}
}
}
Answer by Happeloy · Jul 11, 2020 at 12:08 AM
You're setting the target position after the rotation is done. And when you set it, you set it to the current mouse position, which has most likely moved since you actually pressed your mouse. I guess that is your problem. Instead, you should store the mouse position in your first if-statement, when you check for the mouse down, and use that position when you set the new goal position.