I want the node to move in the right direction but the impulse to be with set strength.
let node: SKSpriteNode!;
node = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(50, 50));
node.physicsBody = SKPhysicsBody(rectangleOfSize: node.size);
node.physicsBody?.affectedByGravity = false;
node.physicsBody?.allowsRotation = false;
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
node.physicsBody?.velocity = CGVectorMake(0, 0);
// ver 1
node.physicsBody?.applyImpulse(CGVectorMake((0.4) * (location.x - node.position.x), (0.4) * (location.y - node.position.y)), atPoint: CGPointMake(position.x,position.y));
// ver 2
let offset:CGPoint = self.vecSub(location, b: ghost.position);
let direction: CGPoint = self.vecNormalize(offset);
var len: CGPoint = self.vecMult(direction, b: 40);
let impulseVector:CGVector = CGVectorMake(len.x, len.y);
ghost.physicsBody?.applyImpulse(impulseVector);
}
func vecAdd(a: CGPoint, b:CGPoint) -> CGPoint {
return CGPointMake(a.x + b.x, a.y + b.y);
}
func vecSub(a: CGPoint, b:CGPoint) -> CGPoint {
return CGPointMake(a.x - b.x, a.y - b.y);
}
func vecMult(a: CGPoint, b:CGFloat) -> CGPoint {
return CGPointMake(a.x * b, a.y * b);
}
func vecLenght(a:CGPoint)->CGFloat{
return CGFloat( sqrtf( CFloat(a.x) * CFloat(a.x) + CFloat(a.y) * CFloat(a.y)));
}
func vecNormalize(a:CGPoint)->CGPoint{
let len : CGFloat = self.vecLenght(a);
return CGPointMake(a.x / len, a.y / len);
}
version 1 is horrible
version 2 is okay, but is too expensive
version 3: something not expensive and to apply impulse with 15-100 strength, because if the touch is at the edges of the screen the node should move only 15-100 of its current possition without reaching the touch position