- Home /
Question by
Ben555 · Sep 16, 2020 at 01:23 PM ·
c#rotation3dmouseclick
Need to rotate an object towards mouse click
void Start()
{
targetPosition = transform.position;
plane = new Plane(Vector3.up, new Vector3(0, height, 0));
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out float distance))
{
targetPosition = ray.GetPoint(distance);
}
}
float distanceToDestination = Vector3.Distance(transform.position, targetPosition);
if (distanceToDestination > (Time.deltaTime * speed))
{
transform.position += (targetPosition - transform.position).normalized * speed * Time.deltaTime;
}
else
{
transform.position = targetPosition;
}
}
So far it moves towards mouse click, but I would like it to rotate first. I would think if I attach an empty (which represents the front of the Object) and then it rotates towards where the mouse was clicked. It also needs to stay at a height of y = 40 and rotate only on the y axis.
rotation-help.png
(68.1 kB)
Comment
Best Answer
Answer by ArminAhmadi · Sep 16, 2020 at 05:34 PM
See if this helps.
private Vector3 targetPosition;
private Plane plane;
public float moveSpeed = 3f;
public float turnSpeed = 3f;
public float angleLimit = 5f;
public float height = 1f;
public bool waitForRotation = true;
private void Start()
{
targetPosition = transform.position;
plane = new Plane(Vector3.up, new Vector3(0, height, 0));
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out float distance))
{
targetPosition = ray.GetPoint(distance);
}
}
if(targetPosition != transform.position)
{
Quaternion targetRotation = Quaternion.LookRotation(targetPosition - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
if (!waitForRotation || Quaternion.Angle(targetRotation, transform.rotation) < angleLimit)
{
float distanceToDestination = Vector3.Distance(transform.position, targetPosition);
if (distanceToDestination > (Time.deltaTime * moveSpeed))
{
transform.position += (targetPosition - transform.position).normalized * moveSpeed * Time.deltaTime;
}
else
{
transform.position = targetPosition;
}
}
}
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
The vision of a camera (displayed as a 3D Cone) needs to rotate towards the player 1 Answer
How can I add a rotation to my bullets when they are shot? 1 Answer
How to change Vector3 if an objects rotation is a certain number? 1 Answer
How do i get the Raycast rotation? 1 Answer