user7433272
user7433272

Reputation:

how to get the force being applied on an object in SpriteKit (Swift)

So I am kinda new to SpriteKit and I am wondering how to get the amount of force on an object and put it into a variable. When you put force on an object, for example, this code,

line.physicsBody?.applyImpulse(CGVector(dx: 0, dy: -30))

it asks you how much in each direction. Well, I want to do the opposite. I want to get the amount of force that the object has and what direction.

Upvotes: 0

Views: 359

Answers (1)

GlorySaber
GlorySaber

Reputation: 367

An impulse a force that lasts for a single instant. The object can only applies a force on another physics body when it collides relative to its velocity and mass.

If your looking to find your objects current avg speed, you use sprite.physicsbody?.velocity

or you can check if the object is moving with

physicsbody?.isResting

if you want to calculate the average force being applied on an object between frames you would have to calculate the magnitude of the change in position between the last update cycle and then multiply by the objects mass like so.

var lastPosition: CGPoint?
 var avgForce: CGPoint?

func updatedForce(for sprite: SKSprite, timeDelta: Double) {
guard let lastPosition = lastPosition, let currentVelocity = currentVelocity) else {
lastPosition = sprite.position
}

let position = sprite.position
let mass = sprite.physicsbody.mass
var changeInX = position.x - lastPosition.x
var changeInY = position.y - lastPosition.y
avgForce = CGPoint(x: changeInX * mass, y: changeInY * mass)
}`

I apologize for any formatting issues or incorrect spellings, made this from my iPhone and will correct later.

Upvotes: 0

Related Questions