根据物体速度和旋转找到所需的点

时间:2014-03-23 00:03:40

标签: ios objective-c math sprite-kit vector-graphics

我希望找到敌人物体前方200像素的点。我尝试计算这一点的方法是:

//all sprites start facing down, so to begin with the point 200 pixels infront of the sprite is its current pos -200 on the y axis.
CGPoint predictedPoint = CGPointMake(self.position.x, self.position.y - 200);

//get the direction of this vector from the current position.
predictedPoint = [Utilities MinusVector:predictedPoint Vector2:self.position];
predictedPoint = [Utilities CGPointNormalize:predictedPoint];

//multiply it by 200 to get 200 pixels ahead.
predictedPoint = [Utilities MultiplyVector:predictedPoint Scalar:200];

//work out which way to rotate the enemy based on its velocity. (this code works as the enemies face the way they move!)
CGPoint facingVector = [Utilities MinusVector:self.position Vector2:CGPointMake(self.position.x + self.velocity.x, self.position.y + self.velocity.y)];
float theta = (atan2f(facingVector.y, facingVector.x) - SK_DEGREES_TO_RADIANS(90.0f));

//rotate
float cs = cosf(theta);
float sn = sinf(theta);

float px = predictedPoint.x * cs - predictedPoint.y * sn;
float py = predictedPoint.x * sn + predictedPoint.y * cs;

CGPoint thePoint = CGPointMake(px, py);

NSLog(@"Player x: %f. thePoint x: %f. Player y: %f. thePoint y: %f.", self.position.x, px, self.position.y, py);

1 个答案:

答案 0 :(得分:1)

所以计算应该是

green.center.x = triangle.center.x + 200 * cos( theta );
green.center.y = triangle.center.y + 200 * sin( theta );

其中theta是三角形的当前旋转角度。这假定theta == 0的三角形指向右侧。如果0角度的精灵指向下方,那么我认为您需要减去M_PI_2,例如

green.center.x = triangle.center.x + 200 * cos( theta - M_PI_2 );
green.center.y = triangle.center.y + 200 * sin( theta - M_PI_2 );