Pong – The Finale

We got the game to a point where it was playable.  It’s not perfect, but it is functional.

 

Here are the scripts that we created/modified today.

GameManager.cs (applied to the GameManager object)

using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public static int player1Score = 0;
 public static int player2Score = 0;
public KeyCode resetKey;
public GUISkin scoreSkin;
// Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 if (Input.GetKeyDown (resetKey))
 {
 Debug.Log ("Cheater! Try playing fairly.");
 }
 }
public static void Score(string wallName, Transform ball)
 {
 if (wallName.Equals ("LeftWall"))
 {
 player2Score += 1;
 }
 else
 {
 player1Score += 1;
 }
BallControl.ResetBall (ball);
 }
void OnGUI()
 {
 GUI.skin = scoreSkin;
GUI.Label (new Rect (Screen.width / 2 - 150, 70, 100, 100), 
 player1Score.ToString ());
 GUI.Label (new Rect (Screen.width / 2 + 150, 70, 100, 100), 
 player2Score.ToString ());
 }
}

BallControl.cs (applied to the Ball)

using UnityEngine;
using System.Collections;
public class BallControl : MonoBehaviour {
// Use this for initialization
 void Start () {
 ResetBall (transform);
 }
 
 // Update is called once per frame
 void Update () {
 
 }
public static void ResetBall(Transform ball)
 {
 float startX = GetRandomVelocity ();
 float startY = GetRandomVelocity ();
 
 ball.rigidbody2D.velocity = new Vector2 (startX, startY);
 Vector3 ballPosition = ball.position;
 ballPosition.x = 0f;
 ballPosition.y = 0f;
 ball.position = ballPosition;
 }
private static float GetRandomVelocity()
 {
 float returnVal = Random.Range (-15f, 15f);
 if (System.Math.Abs (returnVal) < 5f)
 {
 returnVal = GetRandomVelocity ();
 }
return returnVal;
 }
void OnCollisionEnter2D(Collision2D collissionInfo)
 {
 if (collissionInfo.collider.tag.Equals ("Player"))
 {
 Vector2 ballVector = rigidbody2D.velocity;
 ballVector.y = ballVector.y / 2 + collissionInfo.rigidbody.velocity.y / 3;
 rigidbody2D.velocity = ballVector;
 }
string colliderName = collissionInfo.transform.name;
 if (colliderName.Equals ("LeftWall") || 
 colliderName.Equals ("RightWall"))
 {
 GameManager.Score (colliderName, transform);
 }
 }
}

 

Also, I shared with the class the source of the tutorials I’ve been following in order to prepare each day for the club.  The creator of the tutorials is “Brackeys” and he can be easily found on YouTube.

Here is a link to the 2D Game Creation tutorial that most resembles what we have done.  Note that Brackeys prefers to use Javascript, where I prefer C Sharp.  Also, I handle some of the scripting a little bit differently than he does.  There are a lot of different paths to get to the same answer in coding.

Leave a Reply

Your email address will not be published. Required fields are marked *