Jump to content

Measure distance in p2


dmigo
 Share

Recommended Posts

There is a player and some obstacles. The obstacles are some random rectangles. 
The task is to get the distance between the player and the nearest object in front of him.

To do so I create lineOfSight in render method. My idea is to find its intersections with the lines forming the boxes, that float around.
The problem is that I can't find the coords of the vertices of the boxes, as long as they are rotated.

So there are basically two questions:

  • how to find the vertices of the objects?
  • is it a way to go? I mean, maybe there are some better approaches to this task.


Here is my code. You can simply copy it and paste here, to see what it does.

Link to comment
Share on other sites

I'm just learning P2. Yesterday I had similar problem.

MA3VQoi.png

Green = weapon slots and I was wondering how to spawn bullets from them. 


        getBulletStartingPosition() : Phaser.Point
        {
            let x = this.x;
            let y = this.y;
            let angle = this.parent.angle;

            let d = Math.sqrt(x*x + y*y);
            let angleFromCenter = Utils.degrees(Math.asin(x/d));
            
            let offset = Utils.rotateDistance(angle + angleFromCenter, d );
            return new Phaser.Point(this.parent.x + offset.x, this.parent.y + offset.y);
        }

x, y are cords from center of spaceship. 

angle is angle spaceship is heading

Then I calculate distance (d) and angleFromCenter. 

 

I think you can use similar approach to solve your problem.

chiEDoJ.png

// Rectangle = player
// Circle = object 
let x = circle.x - rectangle.x;
let y = circle.y - rectangle.y;
let angle = rectangle.angle;

let distance = Math.sqrt(x*x + y*y);
let angleFromCenter = Utils.degrees(Math.asin(x/d));

let angleRelative = angleFromCenter - angle;

if ( angleRelative > -45 && 45 > angleRelative && 1000 > distance )
{
   // in sight
}
else
{
   // out of sight
}
    static degrees(radians : number) : number
    {
        return radians * 180 / Math.PI;
    }

I didn't test this code, but I think it should work.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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