- Home /
Question by
Alan Fletcher · May 28, 2013 at 01:34 PM ·
c#collisionrigidbody
rigidbody collision and forces
using UnityEngine;
using System.Collections;
public class moveBall : MonoBehaviour {
// Use this for initialization
void Start () {
rigidbody.velocity = new Vector3(-3, 0, 6);
}
// Update is called once per frame
void Update () {
Debug.Log(rigidbody.velocity);
}
void OnCollisionEnter(Collision collision){
if(collision.gameObject.name == "barrier"){
rigidbody.AddForce( new Vector3(0,0,collision.relativeVelocity.z), ForceMode.VelocityChange );
}
if(collision.gameObject.name == "barrier2"){
rigidbody.AddForce( new Vector3(0,0,collision.relativeVelocity.z), ForceMode.VelocityChange );
}
}
}
This is the code im using to move a ball around a field. In the collision code I am reversing the direction on the z axis.
However the ball slows down upon each collision. I want to stop this.
So if anyone knows how to do this or a better way of doing it completely id appreciate it. It is a 2d pong style game.
Thanking You
Comment
For a simple 2D pong game using Forces is probably overkill. When the ball hits a barrier, just reflect the velocity about the normal of the barrier. (Convert the velocity into a speed and a direction vector, then add the normal to the barrier twice, and multiply by speed to get the new velocity.)
can you give a code example for this please if you dont $$anonymous$$d