- Home /
On collision enter not being activated
I am trying to create pong with unity 4.3 as a beginner learning project. As part of this I would like the ball to have a little bit of randomness apon collison, in order to do this i have the following in the ball script:
void OnCollisionEnter(Collision c) {
Debug.Log("afjhas");
}
However it appears that the function is never being activated upon the ball colliding with another object. The objects that they need to collide with possess a rigibody 2d and a 2d colliding box.
The full script of the ball is:
using UnityEngine;
using System.Collections;
public class Ball_scr : MonoBehaviour {
// Use this for initialization
void Start () {
Spawn ();
}
void Spawn(){
Debug.Log("dasdaf");
transform.position = new Vector3(0.0f,0.0f, transform.position.z);
Vector3 newpos=gameObject.transform.position;
System.Random rand=new System.Random();
if(rand.NextDouble() > 0.5){
newpos.x =5;
}else{
newpos.x =-5;
}
newpos.y=(float)GetRandomNumber(-2,2);
gameObject.rigidbody2D.velocity=newpos;
}
double GetRandomNumber(double minimum, double maximum)
{
System.Random rand=new System.Random();
return rand.NextDouble() * (maximum - minimum) + minimum;
}
void OnCollisionEnter(Collision c) {
Debug.Log("afjhas");
}
}
Do you see the collision occuring?
Are you moving the rigidbody with physics or just using Translate?
Yes I do see the collision occuring, I am giving the ball initial movement with: gameObject.rigidbody2D.velocity=newpos; and then just letting unities collision physics do the rest.
Answer by MartinCA · Dec 07, 2013 at 11:28 PM
seeing as you're refering to rigidbody2D, you might want to look at this reference: http://docs.unity3d.com/Documentation/ScriptReference/Collider2D.html
The method you need to implement is OnCollisionEnter2D