2016-11-01 1 views
3

間切片速度を計算し、私は次のように円形の経路に沿って移動するように、「船」ノードを作成しました:は2 SKSpriteNodes

bullet.node.physicsBody.velocity = [ActionHelper getVelocityFrom:bullet.node toNodeB:self.target speed:bullet.speed]; 

船は経路に沿って移動しています。しかし、その弾丸は毎回欠けてしまうでしょう。どのようにして、大砲が目標とする位置を、ある速度で計算することができますか?

+0

2つの物体が衝突する時に、あなたが軌道を計算するために探しているように、あなたはどの時点で把握する必要があり、私に聞こえ、それはいくつかの数学を必要とします – Knight0fDragon

答えて

1

これは私のObjective-Cです(実際にはCの関数です)。動いているターゲットに投射物を発射するソリューションです。あなたは、単に速度にそれを翻訳することができます あなたがこれはあなたのヒットポイントと撮影する角度を与える派生In this SO topic

で見ることができ

、あなたは角度と発射速度を知っているので、それが何かになります以下のような:

`CGVector Velocity = CGVectorMake(speed * cos(theta), speed * sin(theta));` 


BOOL calculateAngleToShoot(CGVector targetVelocity, CGPoint targetPosition, CGPoint selfPos,CGFloat projectileSpeed,CGFloat *theta, CGPoint * hitPoint) 
{ 
    CGFloat dx = targetPosition.x - selfPos.x; 
    CGFloat dy = targetPosition.y - selfPos.y; 

    CGVector v = targetVelocity; 

    CGFloat a = v.dx * v.dx + v.dy * v.dy - projectileSpeed * projectileSpeed; 
    CGFloat b = 2 * (v.dx * dx + v.dy * dy); 
    CGFloat c = v.dx * v.dx + v.dy * v.dy; 

    CGFloat q = b * b - 4 * a * c; 
    if (q < 0) 
    { 
     //Dead End; 
     return NO; 
    } 
    CGFloat t = ((a < 0 ? -1 : 1) * sqrt(q) - b)/(2 * a); 

    // Aim for where the target will be after time t 
    dx += t * v.dx; 
    dy += t * v.dy; 
    *theta = atan2(dy, dx); 

    *hitPoint = CGPointMake(targetPosition.x + v.dx * t, targetPosition.y + v.dy * t); 
    return YES; 
} 
1

私は

は最初、私がターゲットとセンター との間の距離(d)を取得する必要がある答えを得るためにどのようになったいくつかの調査の後中心から標的までの弾丸の時間。 (D)船が円に沿って移動しているので、半径も距離と等しくされているので

CGFloat timeToArriveTarget = bullet.speed/distance; 
CGFloat angularSpeed = bullet.speed/distance; 

角度を探すには、この期間

CGFloat angle = angularSpeed * timeToArriveTarget; 

CGFloat x = self.target.position.x; 
CGFloat y = self.target.position.y; 
CGFloat a = bullet.node.position.x; 
CGFloat b = bullet.node.position.y; 

、最終的に次の式を使用して内で移動しました: 詳細はgetVelocity機能が

で与えられる https://math.stackexchange.com/a/266837

CGPoint targetPt = CGPointMake((x - a) * cos(angle) - (y - b) * sin(angle) + a, (x - a) * sin(angle) + (y - b) * cos(angle) + b); 

bullet.node.physicsBody.velocity = [ActionHelper getVelocityFrom:bullet.node.position toPtB:targetPt speed:bullet.speed]; 

このリンクによって与えています

+(CGVector)getVelocityFrom:(CGPoint)ptA toPtB:(CGPoint)ptB speed:(CGFloat)speed{ 

CGPoint targetPosition = ptB; 
CGPoint currentPosition = ptA; 

double angle = [MathHelper getRotateAngleFrom:currentPosition toTargetPosition:targetPosition]; 
double velocityX = speed * cos(angle); 
double velocityY = speed * sin(angle); 

CGVector newVelocty = CGVectorMake(velocityX, velocityY); 
return newVelocty; 

}

関連する問題