XNA - check if Vector2 is inside Rectangle - vector

What's the best method to check if a Vector2 is inside a Rectangle?
myRect.contains(myVector2) does not work, because it expects a Point or a Rectangle.
I know I could cast the the Vector2 to a Point or even to a Rectangle with a size of 1/1, but I am unsure about performance.
What are your experiences?

One of the overloaded versions of Contains for the Rectangle struct, takes an X and Y coordinate.
Rectangle rect = new Rectangle(-5, -5, 10, 10);
Vector2 myVector2 = Vector2.Zero;
rect.Contains((int)myVector2.X, (int)myVector2.Y)
I assume you're talking about myVector2 representing a point rather than a distance or direction.

While there may be additional execution time in casting vs creating a point like Point(myVector2.X, myVector2.Y), the implications are most likely too small for you to ever notice (generally should avoid premature optimization)
Go with whatever looks cleanest and easier to maintain. If it were me I'd probably just create the new point in the method call...
You could also write an extension method.
public static Point Origin(this Vector2 v)
{
//original proposal
//return new Point( (int)v.X, (int)v.Y );
//better! does correctly round the values
return new Point( Convert.ToInt32(v.X), convert.ToInt32(v.Y));
}
Then you could do something like this rect.Contains(vec.Origin)
Something to remember, though: this method will not actually check if the vector is contained in the rectangle, this will only check if the origin is. Remember, a vector is direction and magnitude.

Related

How to code a pathfinding player in godot using A*?

Iam nooby in godot, I have to use A* to traslate the player to the goal position, but I do not know how to start, pls help!! basically I have just 2 tiles in the tilemap, 1 of them is allowed to pass over it, I have to extract I guess the allowed tile and calculate the distance between the position player with the position goal, getting the real distance and then check cell per cell which has the lowest cost, but I do not know how to do that :c
func get_player_init_pos():
var pos = map_to_world(Vector2(54,1))pos.y += half_cell_size.y
return pos
func is_tile_vacant(pos, direction):
var curr_tile = world_to_map(pos)
var next_tile = get_cellv(curr_tile + direction)
var next_tile_pos = Vector2()
if(next_tile == 0):
next_tile_pos = map_to_world(curr_tile + direction)
else:next_tile_pos = pos
return next_tile_pos
I have this, the first part of the code is to locate the player in the map and the second is for check the tile walls in the map
You could roll your own path finding algorithm. However, there is little point in doing so, since Godot has a AStar class you can use. However, you probably don't need to use that either, because Godot has a navigation system. And that is what I'm going to suggest you to use.
First of all, you can specify both navigation and collision polygons on your tiles. You need to have the navigation polygons. Go ahead and do them.
Second you want to have a Navigation2D in the scene tree and have your TileMap as a child.
And third, you can ask the Navigation2D for a path with get_simple_path, you pass the start and end positions as arguments and you get an array of points that make up the path.
Since you mention A*, I'll briefly explain using the AStar too anyway.
First, you need to add the cells with add_point. It requires ids. It is a good idea to be clever with the ids so you can compute the id for a given position. For example x * width + y if you know the size.
So you can iterate over the tiles in your TileMap and call add_point for each one (You don't need to add cell that are not passable).
Then you need to specify the connections with connect_points (it takes the ids of the points as parameters).
And finally you can call get_point_path passing the start and end ids. Again it gives you a array of points.

Unity3D Linear interpolation from V1 to moving V2

I posted this question on the stack math site, but they are not too excited to see questions including programming. Anyway, now I am here :)
I have an object, which is located at MyTransform.position (Vector)
That object should follow the DesiredPosition (Vector), which is
moving in varius directions with a changing velocity
MaxDelayDistance (float) is the maximum distance my object is allowed
to have to the DesiredPosition.
DelayRecovery (float) are the seconds my object has in order to move
to the DesiredPosition if the MaxDelayDistance is reached.
Time.deltaTime (float) is a term we use to describe the time the last
frame update took. It's value is usually about 0.025f.
private Vector3 GetLerpedPosition(Vector3 DesiredPosition) {
//DesiredPosition now contains the goal
Vector3 dirToDesiredPosition = (DesiredPosition - MyTransform.position).normalized; //Direction to desired position
Vector3 lerpStart = DesiredPosition + (-dirToDesiredPosition * MaxDelayDistance); //Start the lerp at my farthest allowed position
float lerpCurrentT = Vector3.Distance(MyTransform.position, DesiredPosition) / Vector3.Distance(lerpStart, DesiredPosition); //My current fragtion (t) of the lerp
//Now I lerp from lerpStart to DesiredPosition using a calculated fraction
Vector3 result = Vector3.Lerp(
lerpStart,
DesiredPosition,
lerpCurrentT + (DelayRecovery / MaxDelayDistance * Vector3.Distance(MyTransform.position, DesiredPosition) * Time.deltaTime)
);
return result;
}
The main problem is that my object is not following the DesiredPosition smoothly.
It jumps from MaxDelayDistance to DesiredPosition and back.
Somehow the fraction (t) in my Lerp function always results in about 1.005 or about 0.001. Can you spot any problems in my approach?
I see several issue, and I'm not sure of the direction you have choose (at least never seen anything similar before).
Preamble:
Vector3.Distance(lerpStart, DesiredPosition)
this is a constant and is the radius around DesiredPosition.
Here's some problems I noticed:
Problem 1
lerpT is always >=1 for every point more distant more than MaxDelayDistance (outside the radius). So when an object is further distant than MaxDelayDistance it will be immediately moved to DesiredPosition.
Problem 2
DelayRecovery (float) are the seconds my object has in order to move
to the DesiredPosition if the MaxDelayDistance is reached.
Not sure of having completely understood your intricate lerp, btw the statement above seems to be false. DelayRecover is always taken in consideration while lerping despite its distance.
Problem 3
Possible division by zero when you are closed to DesiredPosition (* operator is evaluated before /)
Some considerations
I'll read with more attention your code, and I'll try to figure out the logic behind that. It's something I've never seen.
Some general approach for moving toward a given position:
If start and destination are known and fixed, than lerping (or an ease function) allow to control exactly the travel time incrementing t parameter from 0 to 1.
If destination is moving you can still smooth follow the target using lerp (maybe not the more correct use from a theoretical point of view, nor physical realistic but in any case effective). Lerp factor in this case is a kind of "speed toward the goal". Effectively linear proportional to the distance from the target.
Some physic based approach. Integrate. Define some kind of max speed and max acceleration and calculate the next position (eventually clamp to prevent overshooting and oscillation)
PID controllers. Lot of power, but I always found them hard to tweak.
Consider also to use Vector3.MoveToward, here's how it's implemented:
public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta)
{
Vector3 a = target - current;
float magnitude = a.magnitude;
if (magnitude <= maxDistanceDelta || magnitude == 0f)
{
return target;
}
return current + a / magnitude * maxDistanceDelta;
}
Hope this helps.

How to Find global position of objects in a rotating scene THREE.JS

I am working on a 3D mesh manipulator using this : http://leapmotion.com. So far, I have been able manipulate the points just fine, by 'grabbing' and moving them, however I now want to be able to rotate the mesh and work on the opposite face. What I have done is add an extra object that is called 'rotatable' as Shown below:
scene=new THREE.Scene();
camera = new THREE.PerspectiveCamera(70,window.innerWidth/window.innerHeight,1,8000)
renderer=new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1, maxLights:5 } )
//This is the 'Mesh Scene'
rotatable = new THREE.Object3D()
scene.add(rotatable)
//Mesh we are altering
var material = new THREE.MeshNormalMaterial()
material.side=2
var geom = new THREE.SphereGeometry(200,10,10);
var sphere = new THREE.Mesh(geom, material)
rotatable.add(sphere)
I am then trying to change the vertices of this sphere, but to do so I need to do a 'collision test' in order to see if the vertex is being 'grabbed' This involves check the vertex position and see if it coincides with one of your finger position (psuedoCode below)
if(finger.x == vertex.x && finger.y == vertex.y && finger.z == vertex.z){
vertex.grabbed = true
}
This works fine when the rotatable's rotation is zero, however when it starts to rotate, the collision test will still be testing for the unrotated vertex position (which makes sense). My question is how to find the position of the vertex in its 'scene / global' position. The only way I can think of doing this so far is to calculate the rotation of the 'rotatable' and use this vector to calculate the new vertex position.
I know nothing about math, so this may not be the way to go, and even if it is I will have to struggle through it so hard that I won't ever know if I'm just doing the math incorrectly, or this isn't the way I should go about calculating it. Obviously I'm willing to go through this work, but just want to make sure this is the way to do it, rather then an other simpler method.
If there are any other questions about the code, please let me know, and Thanks in advance for your time!
Isaac
To get the world position of a vertex specified in local coordinates, apply the object's world transform to the vertex like so:
vertex.applyMatrix4( object.matrixWorld );
(I am not familiar with leapmotion, so hopefully it does not impact this answer.)
Tip: maxLights is no longer required. And it is best to avoid material.side = 2. Use material.side = THREE.DoubleSide instead.
You can find the constants here: https://github.com/mrdoob/three.js/blob/master/src/Three.js
three.js r.55

Quaternion rotation matrix unexpectedly has the opposite sense

I have some understanding problem concerning quaternions.
In order to have my world object rotate in the correct way, I need to invert their quaternion rotation while refreshing the object world matrix.
I create the object rotation with this code:
Rotation = Quaternion.RotationMatrix(
Matrix.LookAtRH(Position,
Position + new Vector3(_moveDirection.X, 0, _moveDirection.Y),
Vector3.Up)
);
and refresh the object World matrix like this:
Object.World = Matrix.RotationQuaternion(Rotation)
* Matrix.Translation(Position);
This is not working; it makes the object rotate in the opposite way compared to what it should!
The is the way that makes my object rotate correctly:
Object.World = Matrix.RotationQuaternion(Quaternion.invert(Rotation))
* Matrix.Translation(Position);
Why do I have to invert the object rotation?
This isn't a quaternion problem so much as it is a usage and/or documentation issue with the DirectX call you're using. The transformation the call gives is the one that happens when you move the camera. If you're keeping the camera fixed and moving the world, you're swapping what's moving and what's fixed. These coordinate transformations are inverses of each other, which is why taking the inverse works for you.
You don't need to take an explicit inverse, though. Just swap the order of the first two arguments.

Dynamic closest elements

I have a 2D surface ( Grid ) with 50 elements at different locations.
I need to decide which are the 10 closest elements to a given point.
In addition, the given point is constantly moving and i need to do the calculation on each movement.
I know I can calculate the Euclidean distance to each point on each movement, but I want a faster way.
Thanks.
It sounds like you're trying to come up with a way where you can take the 10 closest points at time t and use those to help you figure out the 10 closest at time t+1. Here's an idea to consider.
When you calculate the 10 closest points, also store the angular direction of where they are relative to your current location. Then, when you move you can calculate the direction in which you moved. Focus your search on the space that's opened up to you (think of a circle around point A and another around point B. The space in B but not in A is where you want to focus your search).
Of course, to do this you need to have some way of searching in a particular area of the grid instead of doing a linear search through an array of points to find those close to you. I'd recommend looking into BSP trees for that. If you're not doing it already, using BSP trees instead of linear search might alone be the performance boost you're looking for.
So, I am going to put all the attempts that I went over to figure out my implementation and hopefully you will be able to figure out the best approach for you project.
I am working on somewhat similar project to what you have mentioned. But in my case I need to do extra cycles once I found the points within a given distance threshold. I have tried few iterations, first I started by creating a distance grid. Keep in mind, I am not working on 2D surface but I don't think changing this to 2D will take much work.
Here is how I developed my distance grid (its so simple even a cave man can do it, I making fun of myself) , Also keep in mind I didn't continue using the grid to finish up my implementation.
public double[][] distanceGrid() {
double[] gridSize = combineArrays(generateClusters(1, 3), generateClusters(12, 15));
double [][] pointsDistanceGrid = new double[gridSize.length][gridSize.length];
for (int i = 0; i < pointsDistanceGrid.length; i++) {
for (int j = 0; j < pointsDistanceGrid[i].length; j++) {
pointsDistanceGrid[i][j] = Math.abs(gridSize[i] - gridSize[j] );
System.out.print(" " + pointsDistanceGrid[i][j]);
}
System.out.println("");
}
return pointsDistanceGrid;
}
As I mentioned I didn't use it.
Since I had to deal with a distance threshold, and I decided before finding "The Nearest" i wanted to see all the points that are closer to the particular point that I am looking at, so I implemented this method.
/**
* Given a point method returns an array with point that are within the limit of threshold.
* #param point
* #return
*/
public double[] pointsWithinThreshold(double point) {
double[] neighbors = new double[bigCluster.length];
for (int i = 0; i < bigCluster.length; i++) {
if (bigCluster[i] != point) {
double distance = 0;
distance = Math.abs(point - bigCluster[i]);
if (distance <= getDistanceThreshold()) {
neighbors[i] = bigCluster[i];
}
}
}
return neighbors;
}
After this I realize I don't really care what are all the closest points so I end up not using this and refractor some of this functionalities to a method where I get the closest member and do recursive DFS.
Let me know if you would like to see that, I didn't put it here coz I thought you only need to know the closest 10 member.
Hope this helps and good luck.

Resources