I am using a ray cast , and the rotation value of the object hit. This code works for primitives I have tested it on. Yet not for the rigid body ,or basic first person character controllers. When placed on these controllers , I get a stutter if in update,and an updated value for one frame if triggered using a bool. My guess is that the rigid body rotation value is set already and it’s trying to implement both behaviors… I really want to get this behavior in my project ,and I refuse to let this beat me, please help xD
Here is the code I am using
using UnityEngine;
using System.Collections;
public class orientPlayer : MonoBehaviour {
GameObject firstRayHit;
GameObject lastHitobject;
//float gravity = -9.8f;
void Awake()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, -Vector3.up, out hitInfo))
{
firstRayHit = hitInfo.transform.gameObject;
lastHitobject = firstRayHit;
}
}
//returns the gameobject hit by our raycast
private GameObject RayToGround()
{
RaycastHit hitInfo;
GameObject _hitObject;
if (Physics.Raycast(transform.position, -Vector3.up, out hitInfo))
{
transform.rotation = Quaternion.FromToRotation(Vector3.right, hitInfo.normal);
}
_hitObject = hitInfo.transform.gameObject;
return _hitObject.transform.gameObject;
}
//orient the player towards the sruface they are standing on . uses the returned gameObject from RayToGround
[ContextMenu("Orient that playaaa")] //This is awesome, lets you right click the componant in the inspector and execute this function =D
void OrientToGround()
{
if (RayToGround() != lastHitobject)
{
transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y, RayToGround().transform.rotation.z, transform.rotation.w);
lastHitobject =RayToGround();
RayToGround();
Debug.Log("OrientingPlayer");
}
}
void FixedUpdate () {
Debug.Log(RayToGround().gameObject.name);
OrientToGround();
}
}