- Home /
Cant align players up vector to surface normal
Hi All,
Probably a simple / stupid question but I can't find the answer and am probably overlooking the obvious. I've been trying to make a simple script for a player to run around the surface of an object, cube/sphere etc... It works great before I align the player to the normal, but the second I do it all breaks, moving towards an axis extreme seems to slow and then completely change direction.
I've attached my full script rather than take up a wall of text here, but I've tried a few alignment methods.
The first was the obvious:
if (Physics.Raycast(transform.position, gravity, out hit, 100.0f))
{
upVector = hit.normal;
}
I found this as a suggestion on one of the posts here, but it has the same issues:
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
I also tried having the player look at the mouse, with their rotation once again around the hit normal but it too broke the same.
Plane playerPlane = new Plane(upVector, transform.position);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast (ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist - playerHeight/2);
transform.LookAt(targetPoint, upVector);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
None of the movement uses world space vectors so I have no idea what's causing it. Any help would be greatly appreciated!
This answer might help:
Thanks, I did try a LookRotation but looking back at it I've noticed a couple errors in how I've set it up. I'll give that another try when I'm back at my PC.
At last! I finally got it working. Thanks for that toromano! For anyone else who is looking for answers, I was simply being an idiot and making silly typos. Here is the working code.
RaycastHit hit;
if (Physics.Raycast(transform.position, gravity, out hit, 100.0f))
{
upVector = hit.normal;
transform.position = hit.point - (gravity.normalized * playerHeight);
}
Plane playerPlane = new Plane(upVector, transform.position);
float hitdist = 0.0f;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (playerPlane.Raycast (ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position, upVector);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}