- Home /
Lock Y transform rotation ? Please help!! Not Rigidbody
Hello :) please help me. I can't lock transform rotation on Y axis. The scripts is too smart for me. Please help! Thanks! (Sometimes character runs off course)
Quaternion lastStickedRotation = Quaternion.identity;
float lastTimeWooshed;
private void MagneticRotate()
{
var stickedRotation = GetMagneticRotation();
if (Time.time > lastTimeWooshed + 0.5f && stickedRotation != lastStickedRotation && Time.time > 1f)
{
WooshSound.Play();
lastTimeWooshed = Time.time;
}
var desRot = Quaternion.Slerp(transform.rotation, stickedRotation, Time.fixedDeltaTime * currentMagneticRotationSpeed);
transform.rotation = desRot;
//transform.Rotate(new Vector3(0f, 1f, 0f), 1f);
lastStickedRotation = stickedRotation;
}
private Quaternion GetMagneticRotation()
{
closestSphereCastHit = null;
if (Physics.SphereCast(transform.position, collider.radius, -transform.up + transform.forward, out RaycastHit hitForward, SPHERECAST_DISTANCE, RayCastLayerMask))
closestSphereCastHit = hitForward;
if (Physics.SphereCast(transform.position, collider.radius, -transform.up, out RaycastHit hitDown, SPHERECAST_DISTANCE, RayCastLayerMask))
{
if (!closestSphereCastHit.HasValue || closestSphereCastHit.Value.distance > hitDown.distance)
closestSphereCastHit = hitDown;
}
if (Physics.SphereCast(transform.position, collider.radius, -transform.up - transform.forward, out RaycastHit hitBack, SPHERECAST_DISTANCE, RayCastLayerMask))
{
if (!closestSphereCastHit.HasValue || closestSphereCastHit.Value.distance > hitBack.distance)
closestSphereCastHit = hitBack;
}
var normal = closestSphereCastHit?.normal ?? Vector3.zero;
var lookRot = Quaternion.LookRotation(Vector3.Cross(transform.right, normal), normal);
return lookRot;
}
Comment
Answer by Lamas17 · Oct 28, 2021 at 09:22 AM
Well I had written thislast night and deleted because it felt out-of-place. Its still not clear if its what you're looking but... here. What I often do is create a helper function that returns any position with my own Y, so my actors keep their feet on the ground, JS example:
function CleanPosition(position:Vector3):Vector3
{
position.y = transform.position.y;
return position;
}
Then anytime you LookAt() or Move(), you should send the vector3 through this method. It might not blend so well into your already written AI, but perhaps it will. Its simple and worked well for me.