I played around with it for a while, but I simply can't figure it out.
I made a tank that fires missiles, and when the missiles hit the walls, I want them to bounce off, but I want them to bounce off to the right angle.
Right now I haven't got any obstacles, the missiles just bounce off when they get outside the viewportRectangle
I made.
Is the solution I'm looking for quite advanced?
Is there a relativly simple way to do it?
I think an easier way to do this is to use the velocity of the missile instead of calculating angles. Say you have a missile that has xVelocity
and yVelocity
to represent its movement horizontally and vertically. Those velocities can be positive or negative to represent left, right, up, or down.
yVelocity
.xVelocity
.This will keep the movement in the opposite axis the same.
Borrowing the image from ChrisF's answer, let's say the missile starts out at position I.
With the xVelocity
and yVelocity
both being positive (in 2D graphics right and down are typically positive) the missile will travel in the direction indicated. Let's just assign values of
xVelocity = 3
yVelocity = 4
When the missile hits the wall at position C, its xVelocity
shouldn't change, but its yVelocity
should be reversed to -4 so that it travels back in the up direction, but keeps going to the right.
The benefit to this method is that you only need to keep track of a missile's xPosition
, yPosition
, xVelocity
, and yVelocity
. Using just these four components and your game's update rate, the missile will always get redrawn at the correct position. Once you get into more complicated obstacles that are not at straight angles or are moving, it will be a lot easier to work with X and Y velocities than with angles.