- Home /
exact vector reflection along collision normal vector
Alright, I have a rigidbody box bouncing against two walls on each side horizontally. Right now I have it so that once the box hits the wall, it'll detect the normal vector of the collision and use vector3.reflect to move in the mirrored direction. Here's the code:
private Vector3 velocity; private float speed;
void Awake () {
velocity = transform.forward;
speed = 10;
}
void FixedUpdate () { transform.position += velocity Time.deltaTime speed; }
void OnCollisionEnter(Collision wall) { foreach(ContactPoint contact in wall.contacts) { velocity=Vector3.Reflect(velocity, contact.normal); return; } }
The problem here is that, because I had no choice but to have the object be non-kinematic, the square ends up moving a tiny bit by itself.. My question is, how do I have it so that the the mirror reflection is perfectly relative to the collision normal vector every time, preventing it from moving arbitrarily after a while. Any help is appreciated.
Note: I don't want the object to go back and forward forever, so I'm not looking for a pingpong code between two positions. Main thing that i want is for the motion to be exactly a reflection relative to the contact normal every time.
EDIT: here's the file to better illustrate what i'm talking about:
http://www.speedyshare.com/files/27869658/mirrorVector2.rar
press play and watch as the box begins to slowly move up or down. this is the problem i'm talking about..
Rounding errors? no cure for that in the foreseeable future.
You won't receive collision information by moving your transform like that. Unity doesn't send collision info when you directly modify the transform
.
basically my question is, why is the cube moving up and down when if i log the velocity and the reflected velocity, all i'm getting is -1 and 1 on the z axis? and if there's a way to stop this from happening
Answer by Mike 3 · Apr 09, 2011 at 03:18 PM
I think this one was fixed on irc, the issues were with moving with transform, and then multiple contact points when moving the cube:
using UnityEngine; using System.Collections;
public class mirrorVector : MonoBehaviour {
private Vector3 velocity;
private float speed;
void Awake () {
velocity = transform.forward;
speed = 2;
}
void FixedUpdate () {
rigidbody.MovePosition(rigidbody.position + velocity * Time.deltaTime * speed);
}
void OnCollisionEnter(Collision bla)
{
foreach(ContactPoint contact in bla.contacts)
{
velocity = Vector3.Reflect(velocity, contact.normal);
return;
}
}
}
Your answer
Follow this Question
Related Questions
How to detect if target is inside an "arc" area? 0 Answers
Finding collision force not working in certain situations. 0 Answers
Collision normal angles. 1 Answer
OnCollisionEnter question 1 Answer