- Home /
Small part of script creating lots of lag
I have these objects that select a random location then rotate to face it then move towards it. If I have about 8 in the game they don't cause any problems but when I put in more than that the game starts to slows down a lot.
I have 25 in game currently most of which are out of the cameras clipping plane but the FPS is about 9.
Code is as follows.
targetposXZ = Vector3(targetpos.x,transform.position.y,targetpos.z);
//face target
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(targetposXZ - transform.position), rotationSpeed * Time.deltaTime);
//move forward
this.rigidbody.AddRelativeForce (0, 0, moveSpeed * Time.deltaTime);
Is there anything I can do to solve this? Gameplay requires quite a few of these objects.
Cheers.
How often are you perfor$$anonymous$$g those operations?
I'm doing it in the update function, so its always going. The objects need to turn and move constantly.
You are applying a distributed force during Update(). While doing that is totally valid, it is not recommended at all. Distributed forces are actually applied to a rigidbody during the physics step, and since Update() is not synched with the physics step, the change in speed of your rigidbody will never be constant. If your game ends up running near 25fps, then your rigidbody will be moving at roughly half the intended speed.
How often do your objects need to turn? How often does the new point to rotate towards get chosen? Since you're slerping the rotation towards the randomly chosen direction, I am led to believe that you don't need to be calling this method every frame. It would be most beneficial to your frame rate to transform this method into a looping coroutine with a randomized delay.
Before I was using -
transform.Translate(Vector3.forward moveSpeed Time.deltaTime);
For the movement but changing it to AddForce seemed to help a bit.
The object needs to constantly turn slowly to face the random point, if i add a delay won't the turning become slightly jumpy?
Ok, I found the issue. It would seem its not the script at fault but rather the child of the gameObject.
Thanks.
Your answer

Follow this Question
Related Questions
Why does my rigidbody slows down at time ? 1 Answer
Lookat Direction by AddTorque? 0 Answers
Problem with rigidbody rotation 2 Answers
Rotating a MeshCollider 0 Answers
Have an object bounce off colliders instead of drift 2 Answers