Making a vector3 z coord have a zero on reflect?

Right so before you laugh at my silly question lets get the laughs out of your system with a joke… why did the chicken fall through the world?.. cause he wasn’t rigid body enough HAHAHA… alright in all seriousness i found this little code and want to implement it so that x,y are always reflected but not the z. so when it hits an angle of an edge i will notice through debugged that it gains a z and will fly off in the distance.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball_Behaviour : MonoBehaviour 
{
	[SerializeField]
	private Vector3 initialVelocity;

	[SerializeField]
	private float minVelocity = 10f;

	private Vector3 lastFrameVelocity;

	private Rigidbody rb;

	void OnEnable()
	{
		rb = GetComponent<Rigidbody> ();
		rb.velocity = initialVelocity;
	}
	
	// Update is called once per frame
	void Update () 
	{
		lastFrameVelocity = rb.velocity;
	}

	void OnCollisionEnter(Collision col)
	{
		Bounce (col.contacts [0].normal);
	}

	private void Bounce(Vector3 collisionNormal)
	{
		var speed = lastFrameVelocity.magnitude;
		var direction = Vector3.Reflect (lastFrameVelocity.normalized, collisionNormal);

		Debug.Log ("Out Direction:" + direction);
		rb.velocity = direction * Mathf.Max (speed, minVelocity);
	}
}

so basically what i want is a way that if the object hits a corner and wants to go in z i can set it to 0 or make it so that the z isn’t possible to start with… i hope this makes sense for what i want.

Thank you for your time
MajorSmurf

Ahh okay I think I know what you mean now (for future Google people, see the comments too, I asked for clarification)

Without looking too much into it, I’d probably force it along the xy-plane by changing it to

Mathf.Max (speed, minVelocity) * Vector3.Scale(new Vector3(1, 1, 0), direction).normalized;

instead of

direction * Mathf.Max (speed, minVelocity); on line 40 (at the very end)

Vector3.Scale(…) will take 2 Vector3s and multiply their corresponding x, y, and z compenents together, so you can multiply by 1 in the x and y to keep whatever the velocity was in the xy axes, but then multiply by 0 in the z to have the velocity there be zero.

For example, Vector3.Scale(new Vector3(1, 1, 0), new Vector3(10, 7, 4)) would give you back an expression equal to new Vector3(10, 7, 0)

By getting rid of the z-component, you need to re-normalize the vector cause it lost its length of 1. Then once it has a length of 1 again, you can multiply by the speed to give you the right size velocity vector.

And a side note, if you’re working with Rigidbodies, you may want to check in the inspector, under “Constraints”, turn on “Freeze Position Z” so that it can’t move (from forces) in the z-axis. I’d still make that change though in the script if you want them to not “lose out on speed” if their direction was not going to be exactly xy-plane parallel.