Question

I'm looking to find the point that is 200 pixels in front of an enemy object. My method to try calculate this point is this:

//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);
Was it helpful?

Solution

So the calculation should be

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

where theta is the current rotation angle of the triangle. This assumes that theta == 0 has the triangle pointing to the right. If the 0 angle has the sprite pointing down, then I think you need to subtract M_PI_2, e.g.

green.center.x = triangle.center.x + 200 * cos( theta - M_PI_2 );
green.center.y = triangle.center.y + 200 * sin( theta - M_PI_2 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top