Search Results

Search found 841 results on 34 pages for 'angle osaxon'.

Page 4/34 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Move penetrating OBB out of another OBB to resolve collision

    - by Milo
    I'm working on collision resolution for my game. I just need a good way to get an object out of another object if it gets stuck. In this case a car. Here is a typical scenario. The red car is in the green object. How do I correctly get it out so the car can slide along the edge of the object as it should. I tried: if(buildings.size() > 0) { Entity e = buildings.get(0); Vector2D vel = new Vector2D(); vel.x = vehicle.getVelocity().x; vel.y = vehicle.getVelocity().y; vel.normalize(); while(vehicle.getRect().overlaps(e.getRect())) { vehicle.setCenter(vehicle.getCenterX() - vel.x * 0.1f, vehicle.getCenterY() - vel.y * 0.1f); } colided = true; } But that does not work too well. Is there some sort of vector I could calculate to use as the vector to move the car away from the object? Thanks Here is my OBB2D class: public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } };

    Read the article

  • Finding the normal of OBB face with an OBB penetrating

    - by Milo
    Below is an illustration: I have an OBB in an OBB (see below for OBB2D code if needed). What I need to determine is, what face it is in, and what direction do I point the normal? The goal is to get the OBB out of the OBB so the normal needs to face outward of the OBB. How could I go about: Finding what face the line is penetrating given the 4 corners of the OBB and the class below: if we define dx=x2-x1 and dy=y2-y1, then the normals are (-dy, dx) and (dy, -dx). Which normal points outward of the OBB? Thanks public class OBB2D { // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(Vector2D center, float w, float h, float angle) { set(center,w,h,angle); } public OBB2D(float left, float top, float width, float height) { set(new Vector2D(left + (width / 2), top + (height / 2)),width,height,0.0f); } public void set(Vector2D center,float w, float h,float angle) { Vector2D X = new Vector2D( (float)Math.cos(angle), (float)Math.sin(angle)); Vector2D Y = new Vector2D((float)-Math.sin(angle), (float)Math.cos(angle)); X = X.multiply( w / 2); Y = Y.multiply( h / 2); corner[0] = center.subtract(X).subtract(Y); corner[1] = center.add(X).subtract(Y); corner[2] = center.add(X).add(Y); corner[3] = center.subtract(X).add(Y); computeAxes(); extents.x = w / 2; extents.y = h / 2; computeDimensions(center,angle); } private void computeDimensions(Vector2D center,float angle) { this.center.x = center.x; this.center.y = center.y; this.angle = angle; boundingRect.left = Math.min(Math.min(corner[0].x, corner[3].x), Math.min(corner[1].x, corner[2].x)); boundingRect.top = Math.min(Math.min(corner[0].y, corner[1].y),Math.min(corner[2].y, corner[3].y)); boundingRect.right = Math.max(Math.max(corner[1].x, corner[2].x), Math.max(corner[0].x, corner[3].x)); boundingRect.bottom = Math.max(Math.max(corner[2].y, corner[3].y),Math.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(new Vector2D(rect.centerX(),rect.centerY()),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0] = corner[1].subtract(corner[0]); axis[1] = corner[3].subtract(corner[0]); // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { axis[a] = axis[a].divide((axis[a].length() * axis[a].length())); origin[a] = corner[0].dot(axis[a]); } } public void moveTo(Vector2D center) { Vector2D centroid = (corner[0].add(corner[1]).add(corner[2]).add(corner[3])).divide(4.0f); Vector2D translation = center.subtract(centroid); for (int c = 0; c < 4; ++c) { corner[c] = corner[c].add(translation); } computeAxes(); computeDimensions(center,angle); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } };

    Read the article

  • Rotating an image in all browsers (canvas in IE?)

    - by Tom
    I finally got to work with canvas only to find out that it is not implemented in IE. I tried explore canvas from google to use it in Internet Explorer, but it's not working for my code (http://uptowar.com/test.php - little bug though that it is not removing the old image when rotating). So, is there an other way to smoothly rotate an image around it's bottom center angle? Maybe javascript? Or is there a way to do it with IE and canvas anyway? Edit: Google Chrome also seems to add an ugly border to the canvas example.. there must be an other smooth way? Edit2: tried a hacky javascript way: it causes mayor lags and corrupts the image (http://uptowar.com/test2.php), anyone knows of a working method?

    Read the article

  • Using Regex, how can I remove certain characters from inside angle-brackets, leaving the characters

    - by Iain Fraser
    Edit: To be clear, please understand that I am not using Regex to parse the html, that's crazy talk! I'm simply wanting to clean up a messy string of html so it will parse Edit #2: I should also point out that the control character I'm using is a special unicode character - it's not something that would ever be used in a proper tag under any normal circumstances Suppose I have a string of html that contains a bunch of control characters and I want to remove the control characters from inside tags only, leaving the characters outside the tags alone. For example Here the control character is the numeral "1". Input The quick 1<strong>orange</strong> lemming <sp11a1n 1class1='jumpe111r'11>jumps over</span> 1the idle 1frog Desired Output The quick 1<strong>orange</strong> lemming <span class='jumper'>jumps over</span> 1the idle 1frog So far I can match tags which contain the control character but I can't remove them in one regex. I guess I could perform another regex on my matches, but I'd really like to know if there's a better way. My regex Bear in mind this one only matches tags which contain the control character. <(([^>])*?`([^>])*?)*?> Thanks very much for your time and consideration. Iain Fraser

    Read the article

  • How can I remove certain characters from inside angle-brackets, leaving the characters outside alone

    - by Iain Fraser
    Edit: To be clear, please understand that I am not using Regex to parse the html, that's crazy talk! I'm simply wanting to clean up a messy string of html so it will parse Edit #2: I should also point out that the control character I'm using is a special unicode character - it's not something that would ever be used in a proper tag under any normal circumstances Suppose I have a string of html that contains a bunch of control characters and I want to remove the control characters from inside tags only, leaving the characters outside the tags alone. For example Here the control character is the numeral "1". Input The quick 1<strong>orange</strong> lemming <sp11a1n 1class1='jumpe111r'11>jumps over</span> 1the idle 1frog Desired Output The quick 1<strong>orange</strong> lemming <span class='jumper'>jumps over</span> 1the idle 1frog So far I can match tags which contain the control character but I can't remove them in one regex. I guess I could perform another regex on my matches, but I'd really like to know if there's a better way. My regex Bear in mind this one only matches tags which contain the control character. <(([^>])*?`([^>])*?)*?> Thanks very much for your time and consideration. Iain Fraser

    Read the article

  • Vector math, finding coördinates on a planar between 2 vectors

    - by Will Kru
    I am trying to generate a 3d tube along a spline. I have the coördinates of the spline (x1,y1,z1 - x2,y2,z2 - etc) which you can see in the illustration in yellow. At those points I need to generate circles, whose vertices are to be connected at a later stadium. The circles need to be perpendicular to the 'corners' of two line segments of the spline to form a correct tube. Note that the segments are kept low for illustration purpose. [apparently I'm not allowed to post images so please view the image at this link] http://img191.imageshack.us/img191/6863/18720019.jpg I am as far as being able to calculate the vertices of each ring at each point of the spline, but they are all on the same planar ie same angled. I need them to be rotated according to their 'legs' (which A & B are to C for instance). I've been thinking this over and thought of the following: two line segments can be seen as 2 vectors (in illustration A & B) the corner (in illustraton C) is where a ring of vertices need to be calculated I need to find the planar on which all of the vertices will reside I then can use this planar (=vector?) to calculate new vectors from the center point, which is C and find their x,y,z using radius * sin and cos However, I'm really confused on the math part of this. I read about the dot product but that returns a scalar which I don't know how to apply in this case. Can someone point me into the right direction? [edit] To give a bit more info on the situation: I need to construct a buffer of floats, which -in groups of 3- describe vertex positions and will be connected by OpenGL ES, given another buffer with indices to form polygons. To give shape to the tube, I first created an array of floats, which -in groups of 3- describe control points in 3d space. Then along with a variable for segment density, I pass these control points to a function that uses these control points to create a CatmullRom spline and returns this in the form of another array of floats which -again in groups of 3- describe vertices of the catmull rom spline. On each of these vertices, I want to create a ring of vertices which also can differ in density (amount of smoothness / vertices per ring). All former vertices (control points and those that describe the catmull rom spline) are discarded. Only the vertices that form the tube rings will be passed to OpenGL, which in turn will connect those to form the final tube. I am as far as being able to create the catmullrom spline, and create rings at the position of its vertices, however, they are all on a planars that are in the same angle, instead of following the splines path. [/edit] Thanks!

    Read the article

  • How to implement curved movement while tracking the appropriate angle?

    - by Vexille
    I'm currently coding a 2D top-down car game which will be turn-based. And since it's turn-based, the cars won't be controlled directly (i.e. with a simple velocity vector that adjusts its angle when the player wants to turn), but instead it's movement path has to be planned beforehand, and then the car needs to follow the path when the turn ends (think Steambirds). This question has some interesting information, but its focus is on homing-missile behaviour, which I kinda had figured out, but doesn't really apply to my case, I think, since I need to show a preview of the path when the player is planning his turn, then have the car follow that path. In that same question, there's an excellent answer by Andrew Russel which mentions Equations of Motion and Bézier's Curve. Some of his other suggestions of implementation are specific to XNA though, so they don't help much (I'm using Marmalade SDK). If I assume Bézier's Curve as the solution of choice, I'm left with one specific problem: I'll have the car's position (the first endpoint) and the target/final position (the last endpoint), but what should I use as the control point (assuming a square/quadratic curve)? And whether I use Bézier's Curve or another parametric equation, I'd still be left with another issue: the car can't just follow the curve, it must turn (i.e. adjust its angle) accordingly. So how can I figure out which way the car should be pointing to at any given point in the curve?

    Read the article

  • What is the proper way to maintain the angle of a gun mounted on a car?

    - by Blair
    So I am making a simple game. I want to put a gun on top of a car. I want to be able to control the angle of the gun. Basically it can go forward all the way so that it is parallel to the ground facing the direction the car is moving or it can point behind the car and any of the angles in between these positions. I have something like the following right now but its not really working. Is there an better way to do this that I am not seeing? #This will place the car glPushMatrix() glTranslatef(self.position.x,1.5,self.position.z) glRotated(self.rotation, 0.0, 1.0, 0.0) glScaled(0.5, 0.5, 0.5) glCallList(self.model.gl_list) glPopMatrix() #This will place the gun on top glPushMatrix() glTranslatef(self.position.x,2.5,self.position.z) glRotated(self.tube_angle, self.direction.z, 0.0, self.direction.x) print self.direction.z glRotated(45, self.position.z, 0.0, self.position.x) glScaled(1.0, 0.5, 1.0) glCallList(self.tube.gl_list) glPopMatrix() This almost works. It moves the gun up and down. But when the car moves around, the angle of the gun changes. Not what I want.

    Read the article

  • How to detect when a device is heading towards a certain location?

    - by Tiger
    Hi, How can I detect when a device is heading towards a certain location? Lets say I have 2 locations- the devices current location, and a location of some restaurant for example- I would like to detect when the device is heading towards that restaurant. (I asked this before with no answers- I thought maybe if I'll rephrase the question...) Thanks.

    Read the article

  • ActionScript Tweening Matrix Transform (big problem)

    - by TheDarkIn1978
    i'm attempting to tween the position and angle of a sprite. if i call the functions without tweening, to appear in one step, it's properly set at the correct coordinates and angle. however, tweening it makes it all go crazy. i'm using an rotateAroundInternalPoint matrix, and assume tweening this along with coordinate positions is messing up the results. works fine (without tweening): public function curl():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle); backCanvas.transform.matrix = internalPointMatrix; } doesn't work properly (with tweening): public function curlUp():void { imageWidth = 400; imageHeight = 600; parameters.distance = 0.5; parameters.angle = 45; distanceTween = new Tween(parameters, "distance", None.easeNone, 0, distance, 1, true); angleTween = new Tween(parameters, "angle", None.easeNone, 0, angle, 1, true); angleTween.addEventListener(TweenEvent.MOTION_CHANGE, animateCurl); } private function animateCurl(evt:TweenEvent):void { backCanvas.x = imageWidth - imageHeight * parameters.distance; backCanvas.y = imageHeight - imageHeight * parameters.distance; var internalPointMatrix:Matrix = backCanvas.transform.matrix; MatrixTransformer.rotateAroundInternalPoint(internalPointMatrix, backCanvas.width * parameters.distance, 0, parameters.angle - previousAngle); backCanvas.transform.matrix = internalPointMatrix; previousAngle = parameters.angle; } in order for the angle to tween properly, i had to add a variable that would track it's last angle setting and subtract it from the new one. however, i still can not get this tween to return the same end position and angle as is without tweening. i've been stuck on this problem for a day now, so any help would be greatly appreciated.

    Read the article

  • C ] How can I handle weird errors from calculating acos / sin / atan2?

    - by Phrixus
    Has anyone seen this weird value while handling sin / cos/ tan / acos.. math stuff? ===THE WEIRD VALUE=== -1.#IND00 ===================== void inverse_pos(double x, double y, double& theta_one, double& theta_two) { // Assume that L1 = 350 and L2 = 250 double B = sqrt(x*x + y*y); double angle_beta = atan2(y, x); double angle_alpha = acos((L2*L2 - B*B - L1*L1) / (-2*B*L1)); theta_one = angle_beta + angle_alpha; theta_two = atan2((y-L1*sin(theta_one)), (x-L1*cos(theta_one))); } This is the code I was working on. In a particular condition - like when x & y are 10 & 10, this code stores -1.#IND00 into theta_one & theta_two. It doesn't look like either characters or numbers :( Without a doubt, atan2 / acos / stuff are the problems. But the problem is, try and catch doesn't work either cuz those double variables have successfully stored some values in them. Moreover, the following calculations never complain about it and never break the program! I'm thinking of forcing to use this value somehow and make the entire program crash... So that I can catch this error.. Except for that idea, I have no idea how I should check whether these theta_one and theta_two variables have stored this crazy values. Any good ideas? Thank you in advance..

    Read the article

  • Calculating the union of 2 longitudal intervals (that may wrap around 180 degrees)

    - by timpatt
    The story: I have a LatLongBounds class that represents an area on the surface of the earth by a latitudinal interval (bounded by north & south - not important to this question) and a longitudinal interval (bounded by east and west; both normalized to a range [-180, 180] - negative being a westerly direction). In order to be able to represent an area that straddles the 180 degree meridian the value of west may be set to be greater than east (eg. the range west = 170, east = -170 will straddle said meridian). In effect the longitudinal interval may wrap around at 180 degrees (or equivalently -180 degrees). My Question: Does anyone have any suggestions as to how I can calculate the union of two longitudinal intervals that may wrap around at 180 degrees. Thanks.

    Read the article

  • Access to Perl's empty angle "<>" operator from an actual filehandle?

    - by Ryan Thompson
    I like to use the nifty perl feature where reading from the empty angle operator <> magically gives your program UNIX filter semantics, but I'd like to be able to access this feature through an actual filehandle (or IO::Handle object, or similar), so that I can do things like pass it into subroutines and such. Is there any way to do this? This question is particularly hard to google, because searching for "angle operator" and "filehandle" just tells me how to read from filehandles using the angle operator.

    Read the article

  • Using the AND and NOT Operator in Python

    - by NoahClark
    Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if self.a, self.b, and self.c are greater than 0, which would mean that I have Angle, Angle, Angle. Below you will see the code that checks for A and B, however when I use just self.a != 0 then it works fine. I believe I'm not using & correctly. Any ideas? Here is how I am calling it: print myTri.detType() class Triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f def detType(self): #Triangle Type AAA if self.a != 0 & self.b != 0: return self.a #If self.a > 10: #return AAA #Triangle Type AAS #elif self.a = 0: #return AAS #Triangle Type ASA #Triangle Type SAS #Triangle Type SSS #else: #return unknown

    Read the article

  • Making AI jump on a spot effectively

    - by Pasquale Sada
    How to calculate, in 3D environment, the closest point, from which an AI character can jump onto a platform? Setup I have an initial velocity V(Vx,Vy,VZ) and a spot where the character stands still at S(Sx,Sy,Sz). What I'm trying to achieve is a successful jump on a spot E(Ex,Ey,Ez) where you have clicked on(only lower or higher spot, because I've in place a simple steering behavior for even terrains). There are no obstacles around. I've implemented a formula that can make him jump in a precise way on a spot but you need to declare an angle: the problem arise when the selected spot is straight above your head. It' pretty lame that the char hang there and can reach a thing that is 1cm above is head. I'll share the code I'm using: Vector3 dir = target - transform.position; // get target direction float h = dir.y; // get height difference dir.y = 0; // retain only the horizontal direction float dist = dir.magnitude ; // get horizontal distance float a = angle * Mathf.Deg2Rad; // convert angle to radians dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle dist += h / Mathf.Tan(a); // correct for small height differences // calculate the velocity magnitude float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 *a)); return vel * dir.normalized; Ended up using the lowest angle (20 degree) and checking for collision on the trajectory. If found any increase the angle. Here some code (to improve the code maybe must stop the check at the highest point of the curve): Vector3 BallisticVel(Vector3 target, float angle) { Vector3 dir = target - transform.position; // get target direction float h = dir.y; // get height difference dir.y = 0; // retain only the horizontal direction float dist = dir.magnitude ; // get horizontal distance float a = angle * Mathf.Deg2Rad; // convert angle to radians dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle dist += h / Mathf.Tan(a); // correct for small height differences // calculate the velocity magnitude float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a)); return vel * dir.normalized; } Vector3 TrajectoryPoint(Vector3 startingPosition, Vector3 startingVelocity, float n ) { float t = 1/60 ; // seconds per time step Vector3 stepVelocity = t * startingVelocity; // m/s Vector3 stepGravity = t * t * Physics.gravity; // m/s/s return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity; } bool CheckTrajectory(Vector3 startingPosition,Vector3 target, float angle_jump) { Debug.Log("checking"); if(angle_jump < 80f) { Debug.Log("if"); Vector3 startingVelocity = BallisticVel(target, angle_jump); for (int i = 0; i < 180; i++) { //Debug.Log(i); Vector3 trajectoryPosition = TrajectoryPoint( startingPosition, startingVelocity, i ); if(Physics.Raycast(trajectoryPosition,Vector3.forward,safeDistance)) { angle_jump += 10; break; // restart loop with the new angle } else continue; } return true; JumpVelocity = BallisticVel(target, angle_jump); } return false; }

    Read the article

  • How can I calculate the angle between two 2D vectors?

    - by Error 454
    I am working on some movement AI where there are no obstacles and movement is restricted to the XY plane. I am calculating two vectors, v, the facing direction of ship 1, and w, the vector pointing from the position of ship 1 to ship 2. I am then calculating the angle between these two vectors using the formula arccos((v · w) / (|v| · |w|)) The problem I'm having is that arccos only returns values between 0° and 180°. This makes it impossible to determine whether I should turn left or right to face the other ship. Is there a better way to do this?

    Read the article

  • how to move the camera behind a model with the same angle? in XNA

    - by Mehdi Bugnard
    I meet are having difficulty in moving my camera behind an object in a 3D world. I would create two view mode. 1: for fps (first person). 2nd: external view behind the character (second person). I searched the net some example but it does not work in my project. Here is my code used to change view if F2 is pressed //Camera double X1 = this.camera.PositionX; double X2 = this.player.Position.X; double Z1 = this.camera.PositionZ; double Z2 = this.player.Position.Z; //Verify that the user must not let the press F2 if (!this.camera.IsF2TurnedInBoucle) { // If the view mode is the second person if (this.camera.ViewCamera_type == CameraSimples.ChangeView.SecondPerson) { this.camera.ViewCamera_type = CameraSimples.ChangeView.firstPerson; //Calcul position - ?? Here my problem double direction = Math.Atan2(X2 - X1, Z2 - Z1) * 180.0 / 3.14159265; //Calcul angle - ?? Here my problem this.camera.position = .. this.camera.rotation = .. this.camera.MouseRadian_LeftrightRot = (float)direction; } //IF mode view is first person else { //....

    Read the article

  • Check if an object is facing another based on angles

    - by Isaiah
    I already have something that calculates the bearing angle to get one object to face another. You give it the positions and it returns the angle to get one to face the other. Now I need to figure out how tell if on object is facing toward another object within a specified field and I can't find any information about how to do this. The objects are obj1 and obj2. Their angles are at obj1.angle and obj2.angle. Their vectors are at obj1.pos and obj2.pos. It's in the format [x,y]. The angle to have one face directly at another is found with direction(obj1.pos,obj2.pos). I want to set the function up like this: isfacing(obj1,obj2,area){...} and return true/false depending if it's in the specified field area to the angle to directly see it. I've got a base like this: var isfacing = function (obj1,obj2,area){ var toface = direction(obj1.pos,obj2.pos); if(toface+area >= obj1.angle && ob1.angle >= toface-area){ return true; } return false; } But my problem is that the angles are in 360 degrees, never above 360 and never below 0. How can I account for that in this? If the first object's angle is say at 0 and say I subtract a field area of 20 or so. It'll check if it's less than -20! If I fix the -20 it becomes 340 but x < 340 isn't what I want, I'd have to x 340 in that case. Is there someone out there with more sleep than I that can help a new dev pulling an all-nighter just to get enemies to know if they're attacking in the right direction? I hope I'm making this harder than it seems. I'd just make them always face the main char if the producer didn't want attacks from behind to work while blocking. In which case I'll need the function above anyways. I've tried to give as much info as I can think would help. Also this is in 2d.

    Read the article

  • How to calculate a point with an given center, angle and radius?

    - by mystify
    In this SO question, someone asked for calculating an angle from three points. I need to do the opposite thing. I want to draw a clock, and I have tiny tick images. An art dude made 60 of them, each with an individual and accurate shadow. So there are 60 distinct images at 10x10 points in size, already correctly rotated in the center of that square. So every 6 degrees one tick image has to be placed. I would just need to calculate the x/y coordinate based on a center point, an radius and an angle. So I have: an center point an radius an angle Is there an easy way to calculate the x/y coordinate with this? Maybe cocoa-touch already has a useful function or method for this?

    Read the article

  • Point of contact of 2 OBBs?

    - by Milo
    I'm working on the physics for my GTA2-like game so I can learn more about game physics. The collision detection and resolution are working great. I'm now just unsure how to compute the point of contact when I hit a wall. Here is my OBB class: public class OBB2D { private Vector2D projVec = new Vector2D(); private static Vector2D projAVec = new Vector2D(); private static Vector2D projBVec = new Vector2D(); private static Vector2D tempNormal = new Vector2D(); private Vector2D deltaVec = new Vector2D(); // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(float centerx, float centery, float w, float h, float angle) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(centerx,centery,w,h,angle); } public OBB2D(float left, float top, float width, float height) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(left + (width / 2), top + (height / 2),width,height,0.0f); } public void set(float centerx,float centery,float w, float h,float angle) { float vxx = (float)Math.cos(angle); float vxy = (float)Math.sin(angle); float vyx = (float)-Math.sin(angle); float vyy = (float)Math.cos(angle); vxx *= w / 2; vxy *= (w / 2); vyx *= (h / 2); vyy *= (h / 2); corner[0].x = centerx - vxx - vyx; corner[0].y = centery - vxy - vyy; corner[1].x = centerx + vxx - vyx; corner[1].y = centery + vxy - vyy; corner[2].x = centerx + vxx + vyx; corner[2].y = centery + vxy + vyy; corner[3].x = centerx - vxx + vyx; corner[3].y = centery - vxy + vyy; this.center.x = centerx; this.center.y = centery; this.angle = angle; computeAxes(); extents.x = w / 2; extents.y = h / 2; computeBoundingRect(); } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0].x = corner[1].x - corner[0].x; axis[0].y = corner[1].y - corner[0].y; axis[1].x = corner[3].x - corner[0].x; axis[1].y = corner[3].y - corner[0].y; // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { float l = axis[a].length(); float ll = l * l; axis[a].x = axis[a].x / ll; axis[a].y = axis[a].y / ll; origin[a] = corner[0].dot(axis[a]); } } public void computeBoundingRect() { boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x)); boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y)); boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x)); boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } public void moveTo(float centerx, float centery) { float cx,cy; cx = center.x; cy = center.y; deltaVec.x = centerx - cx; deltaVec.y = centery - cy; for (int c = 0; c < 4; ++c) { corner[c].x += deltaVec.x; corner[c].y += deltaVec.y; } boundingRect.left += deltaVec.x; boundingRect.top += deltaVec.y; boundingRect.right += deltaVec.x; boundingRect.bottom += deltaVec.y; this.center.x = centerx; this.center.y = centery; computeAxes(); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center.x,center.y,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center.x,center.y,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } public static float distance(float ax, float ay,float bx, float by) { if (ax < bx) return bx - ay; else return ax - by; } public Vector2D project(float ax, float ay) { projVec.x = Float.MAX_VALUE; projVec.y = Float.MIN_VALUE; for (int i = 0; i < corner.length; ++i) { float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay); projVec.x = JMath.min(dot, projVec.x); projVec.y = JMath.max(dot, projVec.y); } return projVec; } public Vector2D getCorner(int c) { return corner[c]; } public int getNumCorners() { return corner.length; } public static float collisionResponse(OBB2D a, OBB2D b, Vector2D outNormal) { float depth = Float.MAX_VALUE; for (int i = 0; i < a.getNumCorners() + b.getNumCorners(); ++i) { Vector2D edgeA; Vector2D edgeB; if(i >= a.getNumCorners()) { edgeA = b.getCorner((i + b.getNumCorners() - 1) % b.getNumCorners()); edgeB = b.getCorner(i % b.getNumCorners()); } else { edgeA = a.getCorner((i + a.getNumCorners() - 1) % a.getNumCorners()); edgeB = a.getCorner(i % a.getNumCorners()); } tempNormal.x = edgeB.x -edgeA.x; tempNormal.y = edgeB.y - edgeA.y; tempNormal.normalize(); projAVec.equals(a.project(tempNormal.x,tempNormal.y)); projBVec.equals(b.project(tempNormal.x,tempNormal.y)); float distance = OBB2D.distance(projAVec.x, projAVec.y,projBVec.x,projBVec.y); if (distance > 0.0f) { return 0.0f; } else { float d = Math.abs(distance); if (d < depth) { depth = d; outNormal.equals(tempNormal); } } } float dx,dy; dx = b.getCenter().x - a.getCenter().x; dy = b.getCenter().y - a.getCenter().y; float dot = Vector2D.dot(dx,dy,outNormal.x,outNormal.y); if(dot > 0) { outNormal.x = -outNormal.x; outNormal.y = -outNormal.y; } return depth; } public Vector2D getMoveDeltaVec() { return deltaVec; } }; Thanks!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >