In this tutorial, you will learn how to add a local multiplayer to air hockey in Unity. Together with the AI which we programmed earlier, this will provide the players of the game with ultimate freedom – play with friends on one device or play with AI.
Adding a local multiplayer isn’t as simple as just adding another player! It requires a completely new way in which we are handling the input. Let’s do it!
This post contains all the code that’s been written in this YouTube video.
PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public List<PlayerMovement> Players = new List<PlayerMovement>();
// Update is called once per frame
void Update () {
for (int i = 0; i < Input.touchCount; i++)
{
Vector2 touchWorldPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
foreach (var player in Players)
{
if (player.LockedFingerID == null)
{
if (Input.GetTouch(i).phase == TouchPhase.Began &&
player.PlayerCollider.OverlapPoint(touchWorldPos))
{
player.LockedFingerID = Input.GetTouch(i).fingerId;
}
}
else if (player.LockedFingerID == Input.GetTouch(i).fingerId)
{
player.MoveToPosition(touchWorldPos);
if (Input.GetTouch(i).phase == TouchPhase.Ended ||
Input.GetTouch(i).phase == TouchPhase.Canceled)
player.LockedFingerID = null;
}
}
}
}
}
PlayerMovement.cs
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
Rigidbody2D rb;
Vector2 startingPosition;
public Transform BoundaryHolder;
Boundary playerBoundary;
public Collider2D PlayerCollider { get; private set; }
public PlayerController Controller;
public int? LockedFingerID { get; set; }
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
startingPosition = rb.position;
PlayerCollider = GetComponent<Collider2D>();
playerBoundary = new Boundary(BoundaryHolder.GetChild(0).position.y,
BoundaryHolder.GetChild(1).position.y,
BoundaryHolder.GetChild(2).position.x,
BoundaryHolder.GetChild(3).position.x);
}
private void OnEnable()
{
Controller.Players.Add(this);
}
private void OnDisable()
{
Controller.Players.Remove(this);
}
public void MoveToPosition(Vector2 position)
{
Vector2 clampedMousePos = new Vector2(Mathf.Clamp(position.x, playerBoundary.Left,
playerBoundary.Right),
Mathf.Clamp(position.y, playerBoundary.Down,
playerBoundary.Up));
rb.MovePosition(clampedMousePos);
}
public void ResetPosition()
{
rb.position = startingPosition;
}
}
