I created a Pong game following a tutorial, and I managed to make it work, but I was left with a doubt.
The code for the ball is the following:
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
// Use this for initialization
void Start () {
rigidbody.velocity = Vector3.right;
}
// Update is called once per frame
void Update () {
rigidbody.velocity = rigidbody.velocity.normalized;
}
//Collision handler
void OnCollisionEnter(Collision collision){
//If collision takes place against left border:
if (collision.collider.name == "borderLeft")
{
//Incomplete code
}
//If colision takes place against right border:
else if (collision.collider.name == "borderRight")
{
//Incomplete code
}
//If collision takes lace against either the bottom or the top border:
else if (collision.collider.name == "borderBot" || collision.collider.name == "borderTop")
{
rigidbody.velocity = new Vector3(rigidbody.velocity.x,
-rigidbody.velocity.y, //Velocity remains the same both in X as in Z, but it is inverted in Y
rigidbody.velocity.z);
}
//If collision takes place against either the left or the right racket:
else if (collision.collider.name == "RacketLeftPlayer"|| collision.collider.name == "RacketRightPlayer")
{
rigidbody.velocity = new Vector3 (-rigidbody.velocity.x, //This time we only invert velocity in X
rigidbody.velocity.y,
rigidbody.velocity.z);
}
}
}
I tried to increase the ball’s speed by modifying part of the code in this way:
void Update () {
rigidbody.velocity = rigidbody.velocity.normalized *3;
}
It did change the ball’s speed as desired but, as a consequence, the ball stops moving as soon as it collides against the racket, instead of inverting the vector’s X component (“bouncing”), and I have no idea how.
I know I can simply reduce the size of the whole game so that speed 1 suits my desires, but I feel like I will learn more this way.
Thanks in advance for your replies!