i am using the following code attached to a capsule to represent an enemy. the capsule has a child cylinder rotation = (90, 0, 0) and position = (0, 0, 1.75) to act as a pointer. when the capsule hits anything with a collider it will bounce. the code works "almost" the way it should, but is off by a slight amount... anyone have any ideas to make this working properly? demo project: http://www.magestorm.com/temp/BasicAI.unitypackage thanks in advance for any help with this! Code (csharp): using UnityEngine; public class AIMovement : MonoBehaviour { public float minSpeed = 3; public float maxSpeed = 7; private Vector3 velocity; ContactPoint hit; void Start() { float mySpeed1 = Random.Range(minSpeed, maxSpeed); float mySpeed2 = Random.Range(minSpeed, maxSpeed); velocity = new Vector3(mySpeed1, 0, mySpeed2); } void FixedUpdate() { // lock up/down movement velocity.y = 0; transform.Translate(velocity * Time.deltaTime, Space.World); //rotate so pointer is pointing at forward movement direction transform.rotation = Quaternion.LookRotation(hit.normal); } void OnCollisionEnter(Collision coll) { hit = coll.contacts[0]; velocity = Vector3.Reflect(velocity, hit.normal); // reflect the velocity } }
It is not a good idea to use a Physics based call back in a translation based system. You are attempting to use the physics system to give you a response, when you are not letting the physics system manage the movement. In your case, I would simply let the physics do the work. give it a rigidbody, and just set it's velocity rather than translate the object. You will get much better results that way.
very helpful link: http://answers.unity3d.com/questions/196896/help-with-bounce-agnle-and-velocity-change.html?sort=oldest final code: Code (csharp): using UnityEngine; public class AIMovement : MonoBehaviour { public float startVel = 5; private Vector3 velocity; void Start() { velocity = new Vector3(0, 0, startVel);//move only in the forward direction } void FixedUpdate() { velocity.y = 0; // make sure velocity is strictly horizontal transform.Translate(velocity * Time.deltaTime, Space.World); } void OnCollisionEnter(Collision coll) { if (coll.collider.tag == "Wall" || coll.collider.tag == "Player") { ContactPoint hit = coll.contacts[0]; Vector3 normal = hit.normal; normal.y = 0; Debug.DrawRay(hit.point, normal, Color.green, 0.3f); // draw green normal Debug.DrawRay(hit.point, -velocity, Color.red, 0.3f); // draw red "in" velocity velocity = Vector3.Reflect(velocity, normal); // reflect the velocity Ray ray = new Ray(hit.point, velocity); transform.LookAt(transform.position + ray.direction); Debug.DrawRay(hit.point, velocity, Color.blue, 0.3f); // draw blue "out" velocity } } }