- Home /
Using Vector3 with multiple directions
Hello! I am currently making a 3d Pong game for an assignment using Unity. However, I have run into an issue with my ball movement using Vector3 & Rigidbody, It can only move in one direction. At the same time. It can't go both left and up at the same time, However it just goes in one direction before hitting a surface and then bounces back in the opposite direction, the only time it's height changes is if I hit it with the top or bottom of my paddles.
Code being used for the ball: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Balls : MonoBehaviour
{
public int Speed = 100;
Rigidbody Rigidbody;
Vector3 velocity;
void Start()
{
Rigidbody = GetComponent<Rigidbody>();
Rigidbody.velocity = Vector3.right * Speed;
}
void FixedUpdate()
{
Rigidbody.velocity = Rigidbody.velocity.normalized * Speed;
velocity = Rigidbody.velocity;
}
public void OnCollisionEnter(Collision collision)
{
Rigidbody.velocity = Vector3.Reflect(velocity, collision.contacts[0].normal);
}
}
Any help is appreciated!
Answer by jackmw94 · Feb 16 at 01:47 PM
I think it makes perfect sense that this happens, since you're starting your ball at a 90 degree angle from the paddle it'll be reflected back out the exact way it came.
Given that you're bouncing off the paddle using reflection, the ball will maintain the same heading throughout the game. This isn't necessarily a problem but I think you might get a more pong-like game by starting your ball's velocity in a direction that isn't perpendicular to the paddle:
Rigidbody.velocity = new Vector3(1f, 0.5f, 0.5f).normalized * Speed;
To add variation you could randomise the direction in which the ball starts. Happy to lend a hand with implementing that should you want to but I'll wait to see if this answer is any help first!
It moves correctly now, thank you! However now it doesn't collide with anything, so I'll have to figure that one out to