3

My entity is supposed to move in straight line toward the mouse. It's close, but not quite there yet. Here's a working demo to show you what I mean.

And here's a screenshot: Entity not moving in a straight line. The red represents the path the mouse took. As you can see, the entity does not take the same path.

Relevant code:

EntityPlayer = ig.Entity.extend({

    movementspeed: 400,

    update: function() {
        this.parent();
        this.move_toward_coord(ig.input.mouse.x, ig.input.mouse.y);
    },

    move_toward_coord: function(x, y) {
        var distance_to_target_x = x - this.pos.x - this.size.x / 2;
        var distance_to_target_y = y - this.pos.y - this.size.y / 2;
        if(Math.abs(distance_to_target_x) > 1 || Math.abs(distance_to_target_y) > 1) {
            this.vel.x = (distance_to_target_x > 1 ? 1 : -1) * this.movementspeed * (Math.abs(distance_to_target_x) / (Math.abs(distance_to_target_x) + Math.abs(distance_to_target_y)));
            this.vel.y = (distance_to_target_y > 1 ? 1 : -1) * this.movementspeed * (Math.abs(distance_to_target_y) / (Math.abs(distance_to_target_x) + Math.abs(distance_to_target_y)));
        } else {
            this.vel.y = 0;
            this.vel.x = 0;
        }
    }

});

I suspect there is something wrong with the move_to_coord method, but after tweaking for too many hours, I'm still not sure what it is...

Why doesn't the ship travel in a straight line?

Joncom
  • 1,465
  • 1
  • 14
  • 25

1 Answers1

4

Ughh!! I figured it out literally seconds after I posted this. Sorry, my bad. It was because of a property called maxVel which was limiting the speed on either the x or y velocity, sometimes one more than the other. >.<

Joncom
  • 1,465
  • 1
  • 14
  • 25
  • 3
    A pretty picture, some concise code, and a solution! win win win. +1 +1 Thanks for sharing. – luser droog Feb 15 '13 at 08:07
  • Indeed, you could turn this into a tutorial on how to make your spaceship do pretty curving paths... – Phil H Feb 15 '13 at 17:04
  • @PhilH I agree. The behavior you were getting is much more interesting than the desired behavior! :) – Cameron Fredman Feb 16 '13 at 01:27
  • @CamFred It's interesting, yes. But it's unpredictable. If the entity is "set" to move at a speed of 400 pixels per second, he wouldn't actually move at that speed. Later, there will be "path curving" to make cornering seem more realistic, but for now it's great that it travels at the correct rate. =) – Joncom Feb 16 '13 at 05:45