Search code examples
swiftsprite-kitskphysicsbody

How to make a physics impulse move the same percentage of the screen on all devices


So what I am trying to do is make it so that a physics impulsee seems to have the same effect on all devices. So basically if I can figure out A way to do the following I will be able to accomplish my goal.

First lets simplify things by taking out all gravity.

Basically I need to calculate the impulse it will take to get a physics object on the far left of the screen to get to the far right of the screen in the same amount of time no matter how big the screen size is.

The reason I ask is I am making a movement system based on the magnitude and angle of a swipe. However I want it to play the same way on every device. I am calculating magnitude by (distance (in virtual points)) / (Time spent making gesture)

Then i am applying it as a physics impulse.

This is the code I am working with:

func Jump(angle: CGFloat, strength: CGFloat)
    {
        if (Ready == true)
        {
            var rangle:CGFloat = angle * CGFloat(M_PI / 180)
            var translate:CGPoint = CGPoint(x: 1, y: 0)
            var vx:CGFloat = ((translate.x * cos(rangle)) - (translate.y * sin(angle)))
            var vy:CGFloat = ((translate.y * cos(rangle)) + (translate.x * sin(rangle)))
            vx *= width
            vy *= height
            vx *= (strength)
            vy *= (strength)
            vx /= 4000
            vy /= 4000

            print("Applying Impulse VX: ")
            print(vx)
            print(" , VY: ")
            print(vy)
            println(" )")
            var velx = Cavity.physicsBody?.velocity.dx
            var vely = Cavity.physicsBody?.velocity.dy
            Cavity.physicsBody?.velocity = CGVector(dx: CGFloat(velx!) / 2, dy: CGFloat(vely!) / 2)
            Cavity.physicsBody?.applyImpulse(CGVectorMake(vx, vy))
            //Cavity.physicsBody?.applyImpulse(CGVectorMake(1000 / width, 1000 / height))
        }
    }

So basically I want it to be so that if a strength of 1 or 2 is passed it will make the same looking result on all devices.


Solution

  • What you can do is make the strength relative to the screen size.

    strengthAdjustment = (1/375*UIScreen.mainScreen().bounds.width) 
    

    This uses the iPhone 6 screen (4.7") width (375 pts) to make the strength = 1.

    With an iPhone 5s the screen will be only 320 pts which and will only require 0.8533 of the impulse strength to move the width of the screen in the same amount of time.

    Hopefully this helps you out.