code below make enemy move towards player.

    //Calculate Distance formula
    double xDiff = player.x - enemy.x;
    double yDiff = player.y - enemy.y;
    double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);

    //find angle
    angle = (int) Math.toDegrees(Math.atan2(yDiff, xDiff));
    if (angle < 0)
        angle += 360;

    xDiff = xDiff / dist;
    yDiff = yDiff / dist;
    x += xDiff * speed;
    y += yDiff * speed;

how to draw line with length 20, same direction as enemy is moving?

enemy.x2 = angle?
enemy.y2 = angle?
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);
  • \$\begingroup\$ What have you tried? Just get a vector towards the target and scale it. blog.wolfire.com/2009/07/… \$\endgroup\$
    – House
    Feb 15, 2014 at 16:01
  • \$\begingroup\$ I know I need distance formula and angle, which i found. But I am not sure how can I use this information to draw a new line. \$\endgroup\$
    – jhon
    Feb 15, 2014 at 16:08
  • \$\begingroup\$ You only need the two points. The point you want to start the line from and the point you want to draw the line towards. Read the three vector math tutorials presented on the wolfire blog. \$\endgroup\$
    – House
    Feb 15, 2014 at 16:12

1 Answer 1

MyLineLength = 10
enemy.x2 =enemy.x1 + (xDif / dist)*MyLineLength //dist!=0 should be tested
enemy.y2 =enemy.y1 + (yDif / dist)*MyLineLength
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);

You don't need to have the angle in order to draw the line if you already know the start and end positions (Vector from player to enemy) Using vectors what you do is to normalize vector, then multiply for length. Basically we did it using separated components.

Study more about vectors and you will see things more easy. Also avoid frequent calls to aTan2 function, is slow.

Anyway answering your original question, if you only have the angle then you'll use Cos and Sin functions (assuming angle in radians):

MyLineLength = 10
enemy.x2 =enemy.x1 + Math.Cos(angle)*MyLineLength
enemy.y2 =enemy.y1 + Math.Sin(angle)*MyLineLength
draw(enemy.x1, enemy.y1, enemy.x2, enemy.y2);
  • \$\begingroup\$ This is the right answer. Note that you need to check for the case where dist is zero (the enemy is right on top of the player) and avoid drawing in that case. Also, when using Math.Cos and Math.Sin, note that the angle should be in radians, not degrees. \$\endgroup\$
    – munificent
    Feb 15, 2014 at 18:09
  • \$\begingroup\$ Yes you are right both cases. I skipped the zero check, and since he doesn't specify the programming language used, I also skipped the radians issue. I should edit some notes, thanks. \$\endgroup\$ Feb 15, 2014 at 18:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .