rigidbody2D moving faster / slower based on mobile screen width?

I have a game object that I spawn off-screen and it moves across the screen using rigidbody2d.MovePosition(). I always want it to hit the mid-point of the screen within X seconds. So with some devices, it will reach mid-point too slow or too fast. I tried dividing the screen width by a number for its speed, but that didn’t lead to the object passing through the middle of the screen at around the same time when I tested it using the device simulator asset.

Any ideas on how to do this?

You could use pixels, ie screen size, as a metric to calculate your positions. Something like that:

  • Get device resolution
  • Decide how many pixels should be moved per unit of time. This is based on the resolution and your X (seconds).
  • Using Time.timeSinceLevelLoad you can get the time that passed since the start of the scene. Alternatively use your own timer to achieve the same
  • Using 2. and 3. you can calculate for any frame how many pixels in total it should have moved from the border
  • Calculate the actual coordinate the object should be at now
  • Cast a ray through the screen at that position (ScreenToWorldPoint? Never used this in 2D)
  • The resulting hit position in the world is the desired position for your object. Move there.

This should allow the object to always reach a position in the middle of your screen in X seconds.
I dont really work with 2D so i hope i did not miss a super simple solution :stuck_out_tongue:

1 Like