Tuesday, June 7, 2016

2d - How do I make an object face the mouse position, but only on one plane?


I want a game object to turn and look towards where the mouse was clicked (in world space). It works well when considering all 3 dimensions, but I really only care for the plane formed by the x and z axis, not the y.


I've tried to fix this by setting the y of the directionTarget to the y of the object's position, but that gives weird results.


My code looks like this:


Quaternion rotationTarget;
float rotationLerpProgress;
float rotationLerpDuration = 1f;


// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{
if (Input.GetMouseButtonDown (0)) {

var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit rayHit;
if (Physics.Raycast (ray, out rayHit)) {
var rayHitPoint = rayHit.point;
var rotationDirection = transform.position - rayHitPoint;
rotationDirection.Normalize ();
//rotationDirection.y = transform.position.y;
rotationTarget = Quaternion.LookRotation (rotationDirection);
rotationLerpProgress = Time.deltaTime;
}

//targetPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
}

if (rotationTarget != transform.rotation) {

transform.rotation = Quaternion.Lerp (transform.rotation, rotationTarget, rotationLerpProgress / rotationLerpDuration);
rotationLerpProgress += Time.deltaTime;

if (rotationLerpProgress >= rotationLerpDuration) {


transform.rotation = rotationTarget;
}

}

}

I must be missing something. How do I do this right?



Answer



I'd project the rotationDirection into the horizontal plane before you normalize it, something like...



var rotationDirection = transform.position - rayHitPoint; 

rotationDirection.y = 0;


rotationDirection.Normalize ();
rotationTarget = Quaternion.LookRotation (rotationDirection);

Note that the order of the subtraction used to define your rotationDirection there results in a vector from the rayHitPoint to transform.position, not the other way - is that as intended?


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...