I'm having an issue with calculating the predicted linear angle a projectile needs to move in to intersect a moving enemy ship for my 2D game.  I've tried following the document , but what I've have come up with is simply awful.  protected Vector2 GetPredictedPosition(float angleToEnemy, ShipCompartment origin, ShipCompartment target) {     // Below obviously won't compile (document wants a Vector, not sure how to get that from a single float?)     Vector2 velocity = target.Thrust - 25f; // Closing velocity (25 is example projectile velocity)     Vector2 distance = target.Position - origin.Position; // Range to close     double time = distance.Length() / velocity.Length(); // Time      // Garbage code, doesn't compile, this method is incorrect     return target.Position + (target.Thrust * time); }   I would be grateful if the community can help point out how this is done correctly.  EDIT  Here is my (working) method following the advice given:  protected Vector2 GetPredictedPosition(ShipCompartment origin, ShipCompartment target, Ship enemyShip, Ship firingShip) {     Vector2 targetVelocity = enemyShip.Direction * enemyShip.Thrust;     Vector2 projectileVelocity = firingShip.Direction * 25f;      Vector2 velocity = targetVelocity - projectileVelocity; // Closing velocity     Vector2 distance = target.Position - origin.Position; // Range to close     double time = distance.Length() / velocity.Length(); // Time      return target.Position + new Vector2(Convert.ToSingle(targetVelocity.X * time), Convert.ToSingle(targetVelocity.Y * time)); }
82124
I saw this question: .  My situation is a little different though.   My target moves, and the shooter moves.  Also, the shooter's velocity is added to the bullets' velocities, i.e. bullets fired while sliding to the right will have a greater velocity toward the right.   What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player.  Using the linked SO solution, unless the player and enemy are stationary, the velocity difference will cause a miss.  How can I prevent that?      Here is the solution presented from the stack overflow answer.  It boils down to solving a quadratic equation of the form:  a * sqr(x) + b * x + c == 0   Note that by sqr I mean square, as opposed to square root. Use the following values:  a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed) b := 2 * (target.velocityX * (target.startX - cannon.X)       + target.velocityY * (target.startY - cannon.Y)) c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y)   Now we can look at the discriminant to determine if we have a possible solution.  disc := sqr(b) - 4 * a * c   If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions:  t1 := (-b + sqrt(disc)) / (2 * a) t2 := (-b - sqrt(disc)) / (2 * a)   Note that if disc == 0 then t1 and t2 are equal.
44294
I am trying to figure out how to determine the direction a collision occurs between two rectangles.  One rectangle does not move. The other rectangle has a velocity in any direction. When a collision occurs, I want to be able to set the position of the moving rectangle to the point of impact.    I seem to be stuck in determining from what direction the impact occurs.  If I am moving strictly vertically or horizontally I manage great detection.  But when moving in both directions at the same time, strange things happen.   What is the best way to determine what direction a collision occurs between two rectangles?
1998
I'm calculating the force of a body hitting water from a high height. So far I've figured out the velocity at the time of collisions would be 40 m/s. The body is 78 kg. I seem to need the time it takes for it to accelerate to a stop after hitting the water but I can't find any concrete numbers for that, what would be a good estimation?
52439
I have two objects (target and player), both have Position (Vector3) and Rotation (Quaternion).  I want the target to rotate and be facing right at the player.  The target, when it shoots something should shoot right at the player.    I've seen plenty of examples of slerping to the player, but I don't want incremental rotation, well, I suppose that would be ok as long as I can make the slerp be 100%, and as long as it actually worked.  FYI - Im able to use the position and rotation to do plenty of other things and it all works great except this last piece I cant figure out.  Code samples run in the Target's class, Position = the targets position, Avatar = the player.  EDIT  Im now using Maik's c# code he has provided and it works great!
52761
I know (from Kinematics) that for an object moving linearly with an acceleration and without air resistance the following equations can be used to determine v(velocity) or x(position of the object) at any time:  $v=v_0+at$  $x=x_0+v_0t+\frac{1}{2}at^2$  Where $x_0$ is the position of the object at the start of accelerated movement, $v_0$ is the velocity at the start of the motion and a is the acceleration.  Now if I want to add air drag, say we take the formula for air drag as:  $D=0.5CA\rho v^2$  $C$ is a coefficent, $A$ is the reference Area, $\rho$ is the density and $v$ the velocity. Since $D$ is a force the air drag results in an acceleration, so in other words: The resulting acceleration is $a-D/m$, however $D$ depends on $v$, which depends on the acceleration. And that's where my problem is, I simply can't wrap my mind around that.  How would I go about getting the Equations for $x$ and $v$ including air drag (and don't forget there's acceleration too)?
64639
I have a basic 2D tower defense game in C++.  Each map is a separate class which inherits from GameState. The map delegates the logic and drawing code to each object in the game and sets data such as the map path. In pseudo-code the logic section might look something like this:    update():   for each creep in creeps:     creep.update()   for each tower in towers:     tower.update()   for each missile in missiles:     missile.update()   The objects (creeps, towers and missiles) are stored in vector-of-pointers. The towers must have access to the vector-of-creeps and the vector-of-missiles to create new missiles and identify targets.  The question is: where do I declare the vectors? Should they be members of the Map class, and passed as arguments to the tower.update() function? Or declared globally? Or are there other solutions I'm missing entirely?  When several classes need to access the same data, where should the data be declared?
100113
Remark: This is not a homework question...It is pure out of theoretical interest. I asked this the mathematics-community a couple days ago and got no answer, so I figured I'd try here.  Most standard physics textbooks compute the force two infinite wires exert on each other, but they remain silent about the case where the wires are finite. Let's say we have two parallel wires carrying a current of equal magnitude in the same direction, both of which have a length $d$ and also seperated by a distance $d$. I now want to find out the force one wire exerts on another, using the Biot-Savart Law.  Let the left wire be positioned at the origin of the $xy$-plane, going along the $y$-axis, and let the other wire be a distance $d$ to the right. We assume the currents are flowing in the positive $y$-direction. Then we first choose a source element (on the left wire) of infinitesimal length $dy$ described by the position vector $\mathbf{r_0} = y_0 \hat{j}$. This constitutes a current source of $I d\vec{l} = (Idy) \hat{j}$.  We then pick an arbitrary field point $P$ on the other wire with position vector $\mathbf{r_p} = x\hat{i} + y \hat{j}$. Then the position vector $\mathbf{r}$ pointing from the source point to the field point is given as  \begin{align*}  \mathbf{r} = \mathbf{r_p} - \mathbf{r_0} = x\hat{i} + (y - y_0) \hat{j}, \end{align*} with $\sqrt{x^2 + (y-y_0)^2}$ being the length of this vector. If we now calculate the crossproduct $d\vec{l} \times \mathbf{r}$, we can write it as \begin{align*} dy \hat{j} \times (x\hat{i} + (y - y_0)\hat{j}) = -dy x \hat{k} \end{align*} Now comes the tricky part. I think I need to setup a double integral, because we are working with infinitesimal force elements $d\mathbf{F}$, each which is given as  $d\mathbf{F} = I d\vec{l} \times \mathbf{B}$. But we also have that \begin{align*} d\mathbf{B} = \frac{\mu_0 I}{4 \pi} \frac{d \vec{l} \times \hat{r}}{r^2}  = \frac{\mu_0 I}{4 \pi} \frac{d \vec{l} \times \mathbf{r}}{r^3} = -\frac{\mu_0 I}{4 \pi} \frac{dyx}{\sqrt{x^2 + (y-y_0)^2}} \hat{k} \end{align*} Hence I need to somehow integrate over $d\mathbf{F}$ and $d\mathbf{B}$. Does anyone have an idea how to do this?
118854
I am currently trying out Unity 3D and I've run into a problem. The problem is I have a car that moves along a road and then when it reaches a corner I would like it to turn the corner and have the model rotate based on its current velocity.  Here is the code I have for moving the object forward:  _velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.deltaTime * 2f; _velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity); Vector3 position = this.transform.position; position += -this.transform.forward * _velocity * Time.deltaTime; this.transform.position = position;   The variables are declared as class members:  private const float MaxVelocity = 10; private float _velocity; private float _acceleration;   This appears to work OK for moving forward. If I applied a rotation it may look OK for a certain velocity, but if the velocity changes, then the rotation seems to quick or to slow.   What I would like (but completely failing at accomplish) is when it comes time to turn, then I would look at the velocity and calculate a smooth rotation so when an object performs a turn it will always end up at the same point regardless of how quick it approaches the corner.  I have tried a number of options, over countless hours, but I'm not having any luck!   Any ideas?  UPDATE #1:  Below is a half-way solution I got, but for now I will add it here and leave the question open for a bit in case someone can provide a better approach.  From what I worked out a LERP rotation from the current direction to the new direction did the trick (kind of!). So, I created a behaviour called VehicleController and in the Awake method I added this:  _target = this.transform.rotation * Quaternion.Euler(0f, 90f, 0f);   This gave me the target rotation relative to my current rotation, i.e. my rotation would have to equal _target for me to be facing in the desired direction. I then added the following to the FixedUpdate method:  //  Rotate if(_doTurn) {     this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity); }   This performed the actual rotation. The key part was setting the third parameter Time.fixedDeltaTime * _velocity. This meant that my rotation speed matched my velocity.   My final FixedUpdate method looked like this:  //  Forward _velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.fixedDeltaTime * 2f; _velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity); Vector3 position = this.transform.position; position += -this.transform.forward * _velocity * Time.fixedDeltaTime; this.transform.position = position;  //  Rotate if(_doTurn) {     this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity); }   In this sample I had a BoxCollider that triggered the turn, so in the OnTriggerEnter method I simply set _doTurn to true.  Now there are a few things with this:   After the turn I had to fix the positioning and rotation a little. The values were off by about .2, but I couldn't really notice any oddness to care. This approach gives a quick snap change in direction which wasn't what I was really after. Ideally I wanted a situation where the turn would be gradual at a certain angle and end in the same point. But, to be honest, it looks OK and that gets me moving on for now! :)   With regards to #1 I think I had to fix some of the position/rotation values because I was using a BoxCollider to trigger the turn so there may be better approaches.
1066
If I have a point which I want to hit at the end or during a parabolic arc, how would I calculate the needed x and y velocity?
99045
Here's the problem: A player starts the game in the 0 coordinate (x=0,y=0). When the user clicks on the screen, it returns the coordinates of the destination. Now the player has to move from its current position A(0.0) to B(x,y). Take into account that B is in the first Quadrant so x>0 and y>0.  How will the player move? I know that I will have to use this: atan2(positionY-destinationY, positionX-destinationX) to get the angle.  Now what? How will the player move with a fixed velocity (which by the way will be a variable, so a player may move faster while using some "items")?  Whose answer is better? What is more accurate? Trigonometry or Linear Algebra?
41459
How can I calculate the position of an object after "firing" it from a fixed point?  I am to create a small game - most likely with canvas (pure HTML, JS based) or Adobe Flash - in which the player fires objects at other obstacles in order to clear them.
82304
When a ball is struck, how can we know in which direction both balls will go when ball is struck? I know the angle at which the ball strikes the other ball matters, but how can we calculate that angle?  I've seen some of the videos to get started with elastic collision. Here is the link:    But it assumes that we know the angle at which the ball strikes other ball. May be I am asking too basic question but I am not a Physics guy so I need to understand how to calculate the angle.   Thanks in advance :)
59270
I have two lines say P1( 0, -1, 0, -1 ) and P2( -1, 0, 0, -1 ). Since I'm working in 2D, there is no Z component. The x,y,z components are normals and the w component is the distance from origin. I am not given the origin or any points on the line.  What method should I use to programmatically determine the point of intersection for these two lines?
70266
In planning some video game camera behavior, I hit a math problem I am having some difficulty with. The camera in this case is restricted to moving along a line and chooses a location along the line to get close to important objects while keeping them in frame.  So to phrase the question in a mathy way:  Given a line (through points $L_1$ and $L_2$ in the drawing), two points $A$ and $B$ not on the line, and an angle $\theta$ (based on the camera's field-of-view), how would you calculate the possible locations of a point $P$ on that line such that $\measuredangle APB = \theta$?  (It looks like there could be zero, one, or two solutions depending on $\theta$ and where the points are in relation to the line)
108419
I'm building an MMO using Node.js, and there are monsters roaming around. I can make them move around on the server using vector variables acceleration, velocity and position.  acceleration = steeringForce / mass;  velocity += acceleration * dTime;  position += velocity * dTime;  Right now I just send the positions over, and tell the players these are the "target positions" of the monsters, and let the monsters move towards the target positions on the client with a speed dependant on the distance of the target position. It works but looks rather strange.  How do I synchronise these properly with the players without looking funny to them, taking into account the server lag?  The problem is that I don't know how to make use of the correct acceleration/velocity values here; right now they just move directly in a straight line to the target position instead of accelerating/braking there properly. How can I implement such behaviour?
110687
Vec2 a, b; // some random vector Vec2 cross = a.Cross(b); RelativeDirection(a,b,cross); // return true if the direction of                               // rotating a to b is counter-clockwise   How do I implement the function RelativeDirection()?  I got some suedo code from the textbook:  if a.Cross(b) &gt; 0 then ... else ...   but the cross product is a vector right? how do you compare it with an integer?
116816
I have an A* implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C# but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A*, I have listed them below.    (Very specific to authors implementation and hard to understand)