**Eric Coleman** | Movement without collision detection is generally quite simple. You have an object or sprite, it has a velocity, and each frame you update it's postion with velocity * time elapsed.
When adding collision detection, you bascially add a check in the movement code to determine if a collision has occured. If it has, then you don't update the sprites' position, otherwise you do.
However, to have the object slide, you need to calculate the velocity vector's projection onto the collision surface. That becomes your new velocity vector for that frame's collision detection of other surfaces. To determine the projection of a vector on another vector is quite simple. Let **V** be your velocity vector, and P1 and P2 be the end points of the line segment. Then calculate **V2** by subtracting P1 - P2. Then the projection of V onto V2 is just ((V dot V2) / Length(V2) ) * Normalized(V2).
Or in code terms.
D = v.x * v2.x + v.y * v2.y = V dot V2
L = sqr(v2.x^2 + v2.y^2) = Length(v2)
v2.x = v2.x / L ' Normalized vector.
v2.y = v2.y / L
V2.x = V2.x * D / L
V2.y = V2.y * D / L
In psuedo code
[code]
Get Applied Velocity
For Each Surface To Collide With
Calculate Projected Velocity, Velocity Projected onto Collision Surface.
Velocity = Projected Velocity
Next
Move Object by Calculated Velocity * elapsed time for frame.
[/code]
The thing to note is that the projected velocity is a temporary value that's calculated each frame, unless of course you want walls to stop you, Otherwise when you're calculating the projected velocity make sure you don't ever overwrite the original velocity of the sprite. |