- Home /
Slerp rotation on collision - C#
Hi all,
I'm having trouble with rotation on collision. Firstly, let me write what I'm trying to accomplish. I have an enemy (right now just a cube) that "wanders" around. When he hits a wall, I have him rotate but that part isn't working. When he hits the wall I would like it to rotate a random degrees and then continue moving. Currently he will hit the wall, rotate a few degrees and then keep going - like the rotation didn't have time to finish. Problem is with this setup, he will just drag along the wall because he didn't fully rotate in another direction.
So it's worth pointing out that the movement works fine. He hits the wall and I know this part is successful because the console reads that it hit the wall like I ask it to on the collision function. Its just the rotation part that doesn't work. Any suggestions?
Here is the code - or at least the important parts:
using System.Collections;
public class RotateOnCollisiont : MonoBehaviour {
public float smooth = 2.0f;
public float wanderSpeed;
public bool wander;
Vector3 wanderDirection;
void Start () {
wander = true;
}
void Update()
{
Wander();
}
void Wander()
{
if (wander == true)
{
float wanderMovement = wanderSpeed * Time.deltaTime;
wanderDirection = transform.position;
rigidbody.velocity = transform.forward * wanderMovement;
transform.LookAt(wanderDirection);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "Wall" && wander == true)
{
Debug.Log ("We hit a wall");
wander = false;
ChangeDirection();
}
}
void ChangeDirection()
{
// Please note I only need it to rotate around the y axis:
Quaternion target = Quaternion.Euler(0, Random.Range(45.0f, 270.0f), 0);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
wander = true;
}
}
Answer by robertbu · Jul 20, 2013 at 06:53 AM
Your issue is line 46. OnCollisionEnter() only gets executed on the frame the collision occurs. Which means that ChangeDirection() only gets called for a single frame. So line 46 only gets call a single time. You can fix your code by moving line 46 into Update(). It will get called every frame, but no rotation will occur unless transform.rotation and target are different.
Thanks @robertbu - this makes sense. I don't see how I missed that.
Answer by username707 · Jul 20, 2013 at 06:43 AM
Is cube having a rigid body? May that be the friction that cube wont complete rotation? Did you check target angle in console?
Your answer
Follow this Question
Related Questions
Basic AI Locked Axis 1 Answer
Follow and Rotate an object 1 Answer
Error with Rotating script 2 Answers
Jitter on Slerp - Raycast 0 Answers