- Home /
Bounce when hitting wall
Hey everyone I'm working on a simple 2d game, but I've run into a problem. Right now if you shoot a projectile and it hits the wall it will bounce perfectly. But if it hits another wall it screws up, which is perfectly makes sense. Why? Because that's how I coded it. Here is a example picture of the problem:
I need help to reformulate the code, and here it is:
public class bullet : MonoBehaviour {
public Vector3 velocity;
public float speed;
void Start () {
velocity = transform.up;
speed = 250;
StartCoroutine (Wait (5));
}
void Update () {
transform.position += velocity * Time.deltaTime * speed;
}
IEnumerator Wait(float seconds) {
yield return new WaitForSeconds(seconds);
Destroy(transform.gameObject);
}
public void OnCollisionEnter(Collision owner) {
if(owner.gameObject.tag == "wall") {
foreach( ContactPoint contact in owner.contacts ) {
velocity = Quaternion.AngleAxis(180, contact.normal) * transform.up * -1;
}
}
}
}
please check the below code, apply it to bullet which should have rigidbody with gravity 0 and a circle collider 2d
public float speed;
private void Update()
{
transform.Translate(Vector2.up * Time.deltaTime * speed);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "wall")
{
ContactPoint2D point = collision.contacts[0];
Vector2 newDir = Vector2.zero;
Vector2 curDire = this.transform.TransformDirection(Vector2.up);
newDir = Vector2.Reflect(curDire, point.normal);
transform.rotation = Quaternion.FromToRotation(Vector2.up, newDir);
}
}
Answer by IgorAherne · Aug 13, 2013 at 05:45 PM
using UnityEngine; using System.Collections;
public class move: MonoBehaviour {
public Vector3 velocity;
public float speed;
bool flipped = false;
void Start () {
velocity = transform.up;
speed = 3;
StartCoroutine (Wait (5));
}
void Update () {
transform.position += velocity * Time.deltaTime * speed;
Debug.DrawRay(transform.position, velocity*10);
}
IEnumerator Wait(float seconds) {
yield return new WaitForSeconds(seconds);
Destroy(transform.gameObject);
}
public void OnCollisionEnter(Collision owner) {
Debug.Log ("Collision");
if(owner.gameObject.tag == "wall") {
foreach( ContactPoint contact in owner.contacts ) {
Debug.Log ("going");
if(!flipped){
velocity = Quaternion.AngleAxis(180, contact.normal) * transform.up*-1;
flipped = true;
}
else{
velocity = Quaternion.AngleAxis(0, contact.normal) * transform.up;
flipped = false;
}
}
}
}
}
I made it kinda work by adding 'return' on both sides so it doesn't execute both. Anyways, sometimes it screws up the direction it's going, but it's atleast a step closer.
edit: added: rigidbody.freezeRotation = true; in start function and it's now working correctly thank you.
edit: well I noticed when it's colliding with a vertical wall and then a horizontal wall (and conversely) it does not bounce correctly. Anybody knows how to fix this?