rigidbody2D.velocity.y not recording C#

Hello :slight_smile:

setup - vertical oblong & horizontal oblong, both have this script attached. a circle tagged as “projectile” is fired at the oblong (using AddForce). the script is supposed to record the x & y velocity of the ball when it hits.

for the vertical oblong this works fine.

for the horizontal oblong this only works on the short edges… on the long edges only the x velocity is recorded. The ball is very definitely moving in the y when it hits.

does anyone have any idea why this doesn’t work on the long sides of the horizontal oblong?

here is the script… I had other stuff going on, but have commented out the other stuff to narrow down what’s not working. I have put the projectile gameobject into a variable incase that was the problem rather than just reading the coll.gameObject.rigidbody2D.velocity for x & y. hasn’t made any difference:

using UnityEngine;
using System.Collections;

public class Breakable : MonoBehaviour {

	public bool vert;
	public float xVel;
	public float yVel;
	GameObject proj;

	void Start ()
	{
		/*if (this.transform.rotation.eulerAngles.z >45f)
			vert = true;
		else
			vert = false;*/
	}


	void OnCollisionEnter2D (Collision2D coll)
	{
		if (coll.gameObject.tag == "Projectile")
		{
			proj = coll.gameObject;
			yVel = proj.rigidbody2D.velocity.y;
			xVel = proj.rigidbody2D.velocity.x;
			//coll.gameObject.SetActive (false);
			//Destroy (this.gameObject);
		}

		/*{
			yVel = coll.gameObject.rigidbody2D.velocity.y;
			xVel = coll.gameObject.rigidbody2D.velocity.x;

			if (vert && xVel > 1f)
				{
					coll.gameObject.SetActive (false);
					Destroy (this.gameObject);
				}
			
			else if (!vert && yVel > 1f)
				{
					coll.gameObject.SetActive (false);
					Destroy (this.gameObject);
				}*/
				

   	}
}

can anybody please tell me why this doesn’t work?.. or have I found a bug?

I think this might help…

	public Vector2 velocity;
	
	void OnCollisionEnter2D (Collision2D col)
	{
		if (col.gameObject.tag == "Projectile")
		{
			velocity.x = col.gameObject.GetComponent<Rigidbody2D>().velocity.x;
			velocity.y = col.gameObject.GetComponent<Rigidbody2D>().velocity.y;

			Destroy (this.gameObject);
		}
	}

EDIT: SOLUTION

Put this inside your PROJECTILE instead of TARGET…

    public Vector2 velocity;

	void OnCollisionEnter2D (Collision2D col)
	{
		if (col.gameObject.tag == "Target")
		{
			velocity.x = gameObject.GetComponent<Rigidbody2D>().velocity.x;
			velocity.y = gameObject.GetComponent<Rigidbody2D>().velocity.y;

			Destroy (col.gameObject);
		}
	}

I tested this and it works :slight_smile: