I have 120 game objects each with a circle collider 2D and a rigidbody 2D. I am moving each of them towards the player with these lines of code:
rb.MovePosition((Vector2)transform.position + (Direction * MoveSpeed * Time.deltaTime));
rb.rotation = Angle;
MoveSpeed = Mathf.Lerp(MinSpeedVar * (1 + (1/(DistanceToTarget * 2))), MaxSpeedVar * (1 + (1/(DistanceToTarget * 2))), Timer);
Angle = Mathf.Atan2(Direction.y, Direction.x) * Mathf.Rad2Deg;
Direction = Target.position - transform.position;
DistanceToTarget = Direction.magnitude;
Direction.Normalize();
With this I am getting around 30 fps at times with a beefy computer, and in my game there will be parts where I will need more than 120 of these objects in the game, so how can I improve performance?
I’d start by just deep profiling your code, and make sure this is the actual code responsible for the poor performance. You may find that it’s something else. Nothing look too bad here in terms of performance cost, so my guess would be the performance loss is coming from something else.
You didn’t include the method calling this, but you’ll also want to make sure you’re calling this in FixedUpdate instead of Update. Though, at the 30FPS you’re getting, that’s not going to improve the performance at all.
If you really getting poor performance from this specific code, and not just the physics interactions in general, then an option would be to use the Jobs system to run these calculations across background threads. It’s not too difficult, but it’s definitely an advanced concept. Jobs can help boost performance.
But profile first. I find it surprising that this code is causing significant a performance drop.