Jump to content

# Measure distance in p2

## 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.

##### Share on other sites

I'm just learning P2. Yesterday I had similar problem. 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. ``````// 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.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible. Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
• ### Recently Browsing   0 members

No registered users viewing this page.

×

• #### Activity

• Leaderboard
×
• Create New...