- Home /
Rotate object to lookAt point and be perpendicular to the ground
My game is a top down game, and to move the player object it just moves towards the mouse point. Right now I have it setup so that the object orients itself to face the point where the user clicked and the object moves to that point. However what I am having an issue with is having the player object face the mouse point and have the player object to correctly stay perpendicular to the ground. Any ideas how to do this?
Typically you'd rotate the player around the world up vector (which should be perpendicular to your ground).
What I tried doing is this:
RaycastHit hitInfo;
Vector3 lookAtPoint = Vector3.zero;
Vector3 localHitPoint = Vector3.zero;
if(Physics.Raycast(r, out hitInfo, 1000.0f, gameInput$$anonymous$$ask))
{
RaycastHit hit;
if (Physics.Raycast(physics$$anonymous$$art.transform.position, -physics$$anonymous$$art.transform.up, out hit, 10.0f, ramp$$anonymous$$ask))
{
physics$$anonymous$$art.transform.localPosition = rootTransform.InverseTransformPoint(hit.point);
}
localHitPoint = rootTransform.InverseTransformPoint(hitInfo.point);
Vector3 delta = localHitPoint - physics$$anonymous$$art.transform.localPosition;
lookAtPoint = new Vector3(localHitPoint.x, physics$$anonymous$$art.transform.localPosition.y, localHitPoint.z);
physics$$anonymous$$art.transform.LookAt(rootTransform.TransformPoint(lookAtPoint, hit.normal));
}
So the first raycast is to deter$$anonymous$$e where the mouse position is (so this is what I want to face). The second raycast within is to deter$$anonymous$$e what we are standing on. I plug this all into my physics$$anonymous$$art object using LookAt and I use the hit.normal to base the world's up vector.
Your code is hinting at a complicated setup that I don't understand. The typical way of fixing this problem is to move your hit.point to the level of the player before doing the LookAt(). Note if your plane that the character is walking on is perfectly flat, you can use Unity's mathematical Plane class and Plane.Raycast() the point. If the mathematical plane is constructed so that it passes through the pivot point of the player, then your LookAt() problem will go away.
Your answer
Follow this Question
Related Questions
SphereCast help 1 Answer
Make character look at mouse position, not world position 3 Answers
LookAt To Only Rotate on Y Axis 2 Answers
Top down look rotation snaps when looking left, right, and back 1 Answer
[HELP]Object Look At Raycast position 2 Answers