Pong Game
Pong Game
Pong Game
Reference
• https://noobtuts.com/unity
Game concept
Game Concept
• If the racket hits the ball at the top corner, then it should bounce off t
owards our top border.
• If the racket hits the ball at the center, then it should bounce off towa
rds the right, and not up or down at all.
• If the racket hits the ball at the bottom corner, then it should bounce
off towards our bottom border.
Camera setup
Creating the walls
Note: as a rule of thumb, everything physical that moves through the game world will need a Rigidbody.
Racket movement
• The rackets have a Rigidbody component and we will use the Rigidbo
dy's velocity property for movement. The velocity is always the move
ment direction multiplied by the speed.
public class MoveRacket : MonoBehaviour
{
void FixedUpdate()
{
float v = Input.GetAxisRaw("Vertical");
}
}
Racket movement
• Use GetComponent to access the racket's Rigidbody component and
then set its velocity
• Add a speed variable to our Script, so that we can control the racket's
movement speed
public float speed = 30;
void FixedUpdate()
{
float v = Input.GetAxisRaw("Vertical");
GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
}
Adding a Movement Axis
using System.Collections;
using UnityEngine;
public class MoveRacket : MonoBehaviour
{
public float speed = 30;
public string axis = "Vertical";
void FixedUpdate()
{
float v = Input.GetAxisRaw(axis);
GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
}
}
Adding a Movement Axis
Adding a Movement Axis
Creating the Ball
Ball Collider & Physics Material
Ball Rigidbody
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float speed = 30;
void Start() {
// Initial Velocity
GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}
}
The Ball <-> Racket Collision Angle
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float speed = 30;
void Start() {
// Initial Velocity
GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}
void OnCollisionEnter2D(Collision2D col) {
// Note: 'col' holds the collision information. If the
// Ball collided with a racket, then:
// col.gameObject is the racket
// col.transform.position is the racket's position
// col.collider is the racket's collider
}
}
Hit position
float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) {
// ascii art:
// || 1 <- at the top of the racket
// ||
// || 0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}
void OnCollisionEnter2D(Collision2D col) {
// Note: 'col' holds the collision information. If the
// Ball collided with a racket, then:
// col.gameObject is the racket
// col.transform.position is the racket's position
// col.collider is the racket's collider