這幾天在處理3D倒影的時候,遇到了如何生成倒影的問題,經過一番查找,找到了一篇關于如何生成倒影的文章,講解得比較詳細,轉載下來,供大家學習參考。
Reflecting a Vector Jan 18, 2006
This is a mainly math tutorial, but don't worry, they won't all be math. It might not be immediately and directly useful, but having an understanding of 3D Math is something that is near essential to many types of modern game programming, and also something not likely to go out of date when new technology comes out. The scenario I'll use for this example is that the player has thrown a grenade, and you want it to bounce off any object that it hits. It should be pretty easy to just look up a formula, but let's try working it out ourselves.
First I'll define what we know already: V - Velocity Vector
N - The Normal Vector of the plane the grenade has struck.
What we need to figure out is: R - The new vector after reflecting velocity in N.
![]() | Here's a diagram showing these vectors. It's a 2D diagram with Vector N aligned to an axis to make it easier to understand what I'm doing( and easier for me to draw.) However we want to solve the general problem for any 3D vectors. |
Remember that the dot product, which returns a scalar value, can be used in projecting a vector onto another axis. (I should point out that the vector N here is a unit vector.) To project V onto N, the formula is (V dot N)*N.
| I worked this out on paper using relationships. In the diagram to the left I centered all the vectors on the origin, except the green ones, because those I'm adding together to try to get R. The actual formula for reflecting a vector then is: R = 2*(V dot N)*N - V |
Now this isn't just reflecting the velocity, it's a bounce, so we actually want -R. We need to negate the formula, giving us:
Vnew = -2*(V dot N)*N + V
You can look the bounce formula this way: (V dot N)*N is the movement towards the plane along the plane normal, subtract it once and V is parallel with the plane, twice and it has bounced off the plane.
Also, when an object bounces some of its speed is lost (how much depends on the object itself and what it hits.) We'll call this value b where b=0.0 means no bounce, and b=1.0 means no loss of speed. So for the final formula, this is what he have:
V new = b * ( -2*(V dot N)*N + V )