- Home /
Question by
Kolalamonkeys · Aug 21, 2020 at 04:47 PM ·
movementclick to move
Move Towards locking one axis
I'm using this MoveTowards script to move the object to wherever the mouse clicks:
public class Test : MonoBehaviour
{
[SerializeField] float speed = 20f;
void Update()
{
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(point);
if (Input.GetMouseButtonDown(0))
{
StopAllCoroutines();
StartCoroutine(MoveTo(transform.position, point, speed));
}
}
IEnumerator MoveTo(Vector3 start, Vector3 point, float speed)
{
while ((transform.position - point).sqrMagnitude > 0.01f)
{
transform.position = Vector3.MoveTowards(transform.position, point, speed * Time.deltaTime);
yield return null;
}
}
Is there any way I can set the y value to always be zero? Thanks!
Comment
Best Answer
Answer by MerpysoupStudio · Aug 21, 2020 at 06:39 PM
@Kolalamonkeys I think this should work, it works for my fps enemies. Although I use a transform instead of a vector3 in the spot where it says point.
Vector3 lookVector = point - transform.position;
lookVector.y = transform.position.y;
Quaternion rotate = Quaternion.LookRotation(lookVector);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, 1);
Your answer
Follow this Question
Related Questions
Player moves to the middle of the room when the level starts (2d point and click) 2 Answers
Objects move toward the center of the screen right after it is created 1 Answer
What is the best way to implement user input and movement when using a State Machine pattern? 1 Answer
How to click on ball to release?,Click on ball to release 1 Answer