- Home /
OnCollision2D never worked
Here are my code, I was trying to make this game object drop on a large collider.
using UnityEngine; using System.Collections;
public class Player_Behavior : MonoBehaviour {
public float gravity;
public float speedX;
public float speedY;
public bool freeFall;
// Use this for initialization
void Start () {
freeFall = true;
gravity = 0.5f;
speedX = 0;
speedY = 0;
}
// Update is called once per frame
void Update () {
gravityPull ();
motionEngine ();
}
void OnCollisionEnter2D (Collision2D collision) {
//if (collision.gameObject.tag == "Platform" && collision.gameObject.transform.position.y < transform.position.y) {
freeFall = false;
speedY = 0;
//}
}
private void gravityPull () {
if (freeFall) {
speedY -= gravity;
} else {
speedY = 0;
}
}
private void motionEngine () {
transform.Translate (speedX * Time.deltaTime, speedY * Time.deltaTime, 0);
}
}
"Stopped" working? So it used to work? What did you change? Do the objects involved in the collision both have 2D colliders and at least one of them have a non-kinematic Rigidbody2D attached?
Sorry I rephrased the question. It never worked.
From your advice I tried to add a rigidbody2d onto one of the object with "is kinematic" unchecked, and the function is still not being called.
Using Transform.Translate in conjunction with physics (eg, colliders) can cause issues like this. Try using Rigidbody2D.$$anonymous$$ovePosition ins$$anonymous$$d. You'll need a rigidbody2D component on your dropped gameobject.
Also if you're using Rigidbody2D.$$anonymous$$ovePosition, make sure to call it in FixedUpdate(), not Update();
It is still not being called...
using UnityEngine; using System.Collections;
public class Player_Behavior : $$anonymous$$onoBehaviour {
public float gravity;
public float speedX;
public float speedY;
public bool freeFall;
public Rigidbody2D rigidBody;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
freeFall = true;
gravity = 0.5f;
speedX = 0;
speedY = 0;
}
// Update is called once per frame
void FixedUpdate () {
gravityPull ();
motionEngine ();
}
void OnCollisionEnter2D (Collision2D collision) {
//if (collision.gameObject.tag == "Platform" && collision.gameObject.transform.position.y < transform.position.y) {
freeFall = false;
speedY = 0;
//}
}
private void gravityPull () {
if (freeFall) {
speedY -= gravity;
} else {
speedY = 0;
}
}
private void motionEngine () {
rigidBody.$$anonymous$$ovePosition (new Vector2(rigidBody.position.x + speedX * Time.fixedDeltaTime, rigidBody.position.y + speedY * Time.fixedDeltaTime));
}
}
Hmm strange. Is your floor collider set as a trigger? If so you should be using OnTriggerEnter2D ins$$anonymous$$d.