Jump to content

Checking distance between player and enemy


gnarvin
 Share

Recommended Posts

Hello again, Im trying to set up my game so that when an enemy gets within a certain distance of the player they start to chase the player. Im trying to use Math.distance but keeps telling me undefined is not a function. Right now I just want to most basic form of this to work so I tried (this is what function runs from the forEach in the update.)

var enemy;if(Math.distance(this.player.x, this.player.y, enemy.x, enemy.y) <= 10){//enemy moves towards player}

I thought this would give me the distance between the player and each enemy and if within 10 it would run the proper code, but I'm not doing something right obviously.

 

Also another question, what a the easiest or best way to determine knock back, Like when played hits an enemy how do I make player bounce back according to the direction they collide. Also same goes for the emitter is there a somewhat simple way to determine the direction of the bullet so the blood splatter makes sense?

Link to comment
Share on other sites

The Math.distance function is pretty simple:

 

 distance: function (x1, y1, x2, y2) {

        var dx = x1 - x2;
        var dy = y1 - y2;

        return Math.sqrt(dx * dx + dy * dy);

    },

 

 

are you sure "enemy" is an object with an "x" and "y" property defined?

 

Link to comment
Share on other sites

Awesome, I knew it was something really obvious, for some reason it didn't click that I needed the Phaser before Math. Thank you so much, this helps me understand how to use the Phaser docs a little better too.

Link to comment
Share on other sites

For knockback and splatter just subtract the shooter's coordinates from the players coordinates, and normalize with the distance you just learned how to calculate :-)

If player coordinates are P=(xp, yp), shot by someone at O=(xo, yo), then the unit-length vector pointing the way the the player's internals will splatter through the exit wound is V=(xo-xp/distance(P,O),yo-yp/distance)

Multiply by a factor proportionate to the strength of the weapon* and add to the speed of the player (assuming you are working with speeds and drag).

 

That's some gruesome math right there, I'm sure kids would listen more at school if teachers used examples like this :-)

*: and be eager to learn about the difference between impulse and kinetic energy to get even more realistic knockbacks :-)

Link to comment
Share on other sites

  • 1 year later...

Avoid sqrt if possible by using squared distance (ex: dist = 2 ; sqdist = 4):

functiondistanceSq(object,target) {

    var xDif = object.x - target.x;
    var yDif = object.y - target.y;

    return (xDif * xDif) + (yDif * yDif);

};

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...