So I’ve got this script that makes my RigidBody rotate when it hits a wall, but it’s kind of a “gross” rotation, I’d like to make it smooth, making it look like more natural, how can I do it?
Should I use Quaternions? If so, how?
Probably start a coroutine to tween it to the new direction… you can use Mathf.MoveTowardsAngle to make sure you’re rotating the shortest way around.
Alternately, you could keep two floats: currentHeading and newHeading, and when you want him to pick a new direction, just set the newHeading. Then every frame see if they are different enough (Mathf.Approximately) to start turning towards. That would trivially let you stop his motion when he is turning, which might look better.
I tried using Mathf.MoveTowardsAngle but it looks like the same, it doesn’t smooth the rotation, it’s just like before
I tried like this, did I do anything wrong?
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime);
var randomint = Random.Range(0, 180);
var fwd = transform.TransformDirection(Vector3.forward);
var target = Random.Range(0, 180);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, 3))
{
if (hit.collider.tag == "Walls")
{
float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.z, target, speed * Time.deltaTime);
transform.eulerAngles = new Vector3(0, randomint, 0);
}
}
}
In line 13 above you are throwing away the “angle” value and just using randomint anyway, so hence it snaps.
This is an excellent reason to look at your compiler warnings since there is probably a little yellow warning saying angle is assigned a value but never used.
And if you’re not using randomint anymore, just delete it to avoid misuse.
Also, the way this is written, the spider will probably keep moving into and back out of the wall, since I don’t think you are stopping him when he is colliding… but give it a try.
So I should replace randomint with angle in the new vector3 right? Sorry for being obnoxious but I’m a kind of illiterate when talking about programming
With this (the one I posted right before your comment) the spider moves in the “right way”, randomly inside the walls, like if it’s in a box, but I’ll try the corrections in morning, I’ll let you know
Tested both, but none of them works out, they let is rotate once for max 90 degress and then it coasts the mesh limits, it blocks after rotating 2 times