Commit 8d61ac10 by Alisa Jung

Autoformat everything: Einrückung mit 2 Leerzeichen, keine Tabs.

parent d87c20d0
...@@ -8,252 +8,252 @@ using System.Collections; ...@@ -8,252 +8,252 @@ using System.Collections;
namespace GamepadInput namespace GamepadInput
{ {
public static class GamePad public static class GamePad
{ {
public enum Button { A, B, Y, X, RightShoulder, LeftShoulder, RightStick, LeftStick, Back, Start } public enum Button { A, B, Y, X, RightShoulder, LeftShoulder, RightStick, LeftStick, Back, Start }
public enum Trigger { LeftTrigger, RightTrigger } public enum Trigger { LeftTrigger, RightTrigger }
public enum Axis { LeftStick, RightStick, Dpad } public enum Axis { LeftStick, RightStick, Dpad }
public enum Index { Any, One, Two, Three, Four } public enum Index { Any, One, Two, Three, Four }
public static bool GetButtonDown(Button button, Index controlIndex) public static bool GetButtonDown(Button button, Index controlIndex)
{ {
KeyCode code = GetKeycode(button, controlIndex); KeyCode code = GetKeycode(button, controlIndex);
return Input.GetKeyDown(code); return Input.GetKeyDown(code);
} }
public static bool GetButtonUp(Button button, Index controlIndex) public static bool GetButtonUp(Button button, Index controlIndex)
{ {
KeyCode code = GetKeycode(button, controlIndex); KeyCode code = GetKeycode(button, controlIndex);
return Input.GetKeyUp(code); return Input.GetKeyUp(code);
} }
public static bool GetButton(Button button, Index controlIndex) public static bool GetButton(Button button, Index controlIndex)
{ {
KeyCode code = GetKeycode(button, controlIndex); KeyCode code = GetKeycode(button, controlIndex);
return Input.GetKey(code); return Input.GetKey(code);
} }
/// <summary> /// <summary>
/// returns a specified axis /// returns a specified axis
/// </summary> /// </summary>
/// <param name="axis">One of the analogue sticks, or the dpad</param> /// <param name="axis">One of the analogue sticks, or the dpad</param>
/// <param name="controlIndex">The controller number</param> /// <param name="controlIndex">The controller number</param>
/// <param name="raw">if raw is false then the controlIndex will be returned with a deadspot</param> /// <param name="raw">if raw is false then the controlIndex will be returned with a deadspot</param>
/// <returns></returns> /// <returns></returns>
public static Vector2 GetAxis(Axis axis, Index controlIndex, bool raw = false) public static Vector2 GetAxis(Axis axis, Index controlIndex, bool raw = false)
{ {
string xName = "", yName = ""; string xName = "", yName = "";
switch (axis) switch (axis)
{ {
case Axis.Dpad: case Axis.Dpad:
xName = "DPad_XAxis_" + (int)controlIndex; xName = "DPad_XAxis_" + (int)controlIndex;
yName = "DPad_YAxis_" + (int)controlIndex; yName = "DPad_YAxis_" + (int)controlIndex;
break; break;
case Axis.LeftStick: case Axis.LeftStick:
xName = "L_XAxis_" + (int)controlIndex; xName = "L_XAxis_" + (int)controlIndex;
yName = "L_YAxis_" + (int)controlIndex; yName = "L_YAxis_" + (int)controlIndex;
break; break;
case Axis.RightStick: case Axis.RightStick:
xName = "R_XAxis_" + (int)controlIndex; xName = "R_XAxis_" + (int)controlIndex;
yName = "R_YAxis_" + (int)controlIndex; yName = "R_YAxis_" + (int)controlIndex;
break; break;
} }
Vector2 axisXY = Vector3.zero; Vector2 axisXY = Vector3.zero;
try try
{ {
if (raw == false) if (raw == false)
{ {
axisXY.x = Input.GetAxis(xName); axisXY.x = Input.GetAxis(xName);
axisXY.y = -Input.GetAxis(yName); axisXY.y = -Input.GetAxis(yName);
}
else
{
axisXY.x = Input.GetAxisRaw(xName);
axisXY.y = -Input.GetAxisRaw(yName);
}
}
catch (System.Exception e)
{
Debug.LogError(e);
Debug.LogWarning("Have you set up all axes correctly? \nThe easiest solution is to replace the InputManager.asset with version located in the GamepadInput package. \nWarning: do so will overwrite any existing input");
}
return axisXY;
} }
else
public static float GetTrigger(Trigger trigger, Index controlIndex, bool raw = false)
{ {
// axisXY.x = Input.GetAxisRaw(xName);
string name = ""; axisXY.y = -Input.GetAxisRaw(yName);
if (trigger == Trigger.LeftTrigger)
name = "TriggersL_" + (int)controlIndex;
else if (trigger == Trigger.RightTrigger)
name = "TriggersR_" + (int)controlIndex;
//
float axis = 0;
try
{
if (raw == false)
axis = Input.GetAxis(name);
else
axis = Input.GetAxisRaw(name);
}
catch (System.Exception e)
{
Debug.LogError(e);
Debug.LogWarning("Have you set up all axes correctly? \nThe easiest solution is to replace the InputManager.asset with version located in the GamepadInput package. \nWarning: do so will overwrite any existing input");
}
return axis;
} }
}
catch (System.Exception e)
{
Debug.LogError(e);
Debug.LogWarning("Have you set up all axes correctly? \nThe easiest solution is to replace the InputManager.asset with version located in the GamepadInput package. \nWarning: do so will overwrite any existing input");
}
return axisXY;
}
public static float GetTrigger(Trigger trigger, Index controlIndex, bool raw = false)
{
//
string name = "";
if (trigger == Trigger.LeftTrigger)
name = "TriggersL_" + (int)controlIndex;
else if (trigger == Trigger.RightTrigger)
name = "TriggersR_" + (int)controlIndex;
static KeyCode GetKeycode(Button button, Index controlIndex) //
{ float axis = 0;
switch (controlIndex) try
{ {
case Index.One: if (raw == false)
switch (button) axis = Input.GetAxis(name);
{ else
case Button.A: return KeyCode.Joystick1Button0; axis = Input.GetAxisRaw(name);
case Button.B: return KeyCode.Joystick1Button1; }
case Button.X: return KeyCode.Joystick1Button2; catch (System.Exception e)
case Button.Y: return KeyCode.Joystick1Button3; {
case Button.RightShoulder: return KeyCode.Joystick1Button5; Debug.LogError(e);
case Button.LeftShoulder: return KeyCode.Joystick1Button4; Debug.LogWarning("Have you set up all axes correctly? \nThe easiest solution is to replace the InputManager.asset with version located in the GamepadInput package. \nWarning: do so will overwrite any existing input");
case Button.Back: return KeyCode.Joystick1Button6; }
case Button.Start: return KeyCode.Joystick1Button7; return axis;
case Button.LeftStick: return KeyCode.Joystick1Button8; }
case Button.RightStick: return KeyCode.Joystick1Button9;
}
break;
case Index.Two:
switch (button)
{
case Button.A: return KeyCode.Joystick2Button0;
case Button.B: return KeyCode.Joystick2Button1;
case Button.X: return KeyCode.Joystick2Button2;
case Button.Y: return KeyCode.Joystick2Button3;
case Button.RightShoulder: return KeyCode.Joystick2Button5;
case Button.LeftShoulder: return KeyCode.Joystick2Button4;
case Button.Back: return KeyCode.Joystick2Button6;
case Button.Start: return KeyCode.Joystick2Button7;
case Button.LeftStick: return KeyCode.Joystick2Button8;
case Button.RightStick: return KeyCode.Joystick2Button9;
}
break;
case Index.Three:
switch (button)
{
case Button.A: return KeyCode.Joystick3Button0;
case Button.B: return KeyCode.Joystick3Button1;
case Button.X: return KeyCode.Joystick3Button2;
case Button.Y: return KeyCode.Joystick3Button3;
case Button.RightShoulder: return KeyCode.Joystick3Button5;
case Button.LeftShoulder: return KeyCode.Joystick3Button4;
case Button.Back: return KeyCode.Joystick3Button6;
case Button.Start: return KeyCode.Joystick3Button7;
case Button.LeftStick: return KeyCode.Joystick3Button8;
case Button.RightStick: return KeyCode.Joystick3Button9;
}
break;
case Index.Four:
switch (button)
{
case Button.A: return KeyCode.Joystick4Button0;
case Button.B: return KeyCode.Joystick4Button1;
case Button.X: return KeyCode.Joystick4Button2;
case Button.Y: return KeyCode.Joystick4Button3;
case Button.RightShoulder: return KeyCode.Joystick4Button5;
case Button.LeftShoulder: return KeyCode.Joystick4Button4;
case Button.Back: return KeyCode.Joystick4Button6;
case Button.Start: return KeyCode.Joystick4Button7;
case Button.LeftStick: return KeyCode.Joystick4Button8;
case Button.RightStick: return KeyCode.Joystick4Button9;
}
break; static KeyCode GetKeycode(Button button, Index controlIndex)
case Index.Any: {
switch (button) switch (controlIndex)
{ {
case Button.A: return KeyCode.JoystickButton0; case Index.One:
case Button.B: return KeyCode.JoystickButton1; switch (button)
case Button.X: return KeyCode.JoystickButton2; {
case Button.Y: return KeyCode.JoystickButton3; case Button.A: return KeyCode.Joystick1Button0;
case Button.RightShoulder: return KeyCode.JoystickButton5; case Button.B: return KeyCode.Joystick1Button1;
case Button.LeftShoulder: return KeyCode.JoystickButton4; case Button.X: return KeyCode.Joystick1Button2;
case Button.Back: return KeyCode.JoystickButton6; case Button.Y: return KeyCode.Joystick1Button3;
case Button.Start: return KeyCode.JoystickButton7; case Button.RightShoulder: return KeyCode.Joystick1Button5;
case Button.LeftStick: return KeyCode.JoystickButton8; case Button.LeftShoulder: return KeyCode.Joystick1Button4;
case Button.RightStick: return KeyCode.JoystickButton9; case Button.Back: return KeyCode.Joystick1Button6;
} case Button.Start: return KeyCode.Joystick1Button7;
break; case Button.LeftStick: return KeyCode.Joystick1Button8;
} case Button.RightStick: return KeyCode.Joystick1Button9;
return KeyCode.None; }
} break;
case Index.Two:
switch (button)
{
case Button.A: return KeyCode.Joystick2Button0;
case Button.B: return KeyCode.Joystick2Button1;
case Button.X: return KeyCode.Joystick2Button2;
case Button.Y: return KeyCode.Joystick2Button3;
case Button.RightShoulder: return KeyCode.Joystick2Button5;
case Button.LeftShoulder: return KeyCode.Joystick2Button4;
case Button.Back: return KeyCode.Joystick2Button6;
case Button.Start: return KeyCode.Joystick2Button7;
case Button.LeftStick: return KeyCode.Joystick2Button8;
case Button.RightStick: return KeyCode.Joystick2Button9;
}
break;
case Index.Three:
switch (button)
{
case Button.A: return KeyCode.Joystick3Button0;
case Button.B: return KeyCode.Joystick3Button1;
case Button.X: return KeyCode.Joystick3Button2;
case Button.Y: return KeyCode.Joystick3Button3;
case Button.RightShoulder: return KeyCode.Joystick3Button5;
case Button.LeftShoulder: return KeyCode.Joystick3Button4;
case Button.Back: return KeyCode.Joystick3Button6;
case Button.Start: return KeyCode.Joystick3Button7;
case Button.LeftStick: return KeyCode.Joystick3Button8;
case Button.RightStick: return KeyCode.Joystick3Button9;
}
break;
case Index.Four:
public static GamepadState GetState(Index controlIndex, bool raw = false) switch (button)
{ {
GamepadState state = new GamepadState(); case Button.A: return KeyCode.Joystick4Button0;
case Button.B: return KeyCode.Joystick4Button1;
case Button.X: return KeyCode.Joystick4Button2;
case Button.Y: return KeyCode.Joystick4Button3;
case Button.RightShoulder: return KeyCode.Joystick4Button5;
case Button.LeftShoulder: return KeyCode.Joystick4Button4;
case Button.Back: return KeyCode.Joystick4Button6;
case Button.Start: return KeyCode.Joystick4Button7;
case Button.LeftStick: return KeyCode.Joystick4Button8;
case Button.RightStick: return KeyCode.Joystick4Button9;
}
state.A = GetButton(Button.A, controlIndex); break;
state.B = GetButton(Button.B, controlIndex); case Index.Any:
state.Y = GetButton(Button.Y, controlIndex); switch (button)
state.X = GetButton(Button.X, controlIndex); {
case Button.A: return KeyCode.JoystickButton0;
case Button.B: return KeyCode.JoystickButton1;
case Button.X: return KeyCode.JoystickButton2;
case Button.Y: return KeyCode.JoystickButton3;
case Button.RightShoulder: return KeyCode.JoystickButton5;
case Button.LeftShoulder: return KeyCode.JoystickButton4;
case Button.Back: return KeyCode.JoystickButton6;
case Button.Start: return KeyCode.JoystickButton7;
case Button.LeftStick: return KeyCode.JoystickButton8;
case Button.RightStick: return KeyCode.JoystickButton9;
}
break;
}
return KeyCode.None;
}
state.RightShoulder = GetButton(Button.RightShoulder, controlIndex); public static GamepadState GetState(Index controlIndex, bool raw = false)
state.LeftShoulder = GetButton(Button.LeftShoulder, controlIndex); {
state.RightStick = GetButton(Button.RightStick, controlIndex); GamepadState state = new GamepadState();
state.LeftStick = GetButton(Button.LeftStick, controlIndex);
state.Start = GetButton(Button.Start, controlIndex); state.A = GetButton(Button.A, controlIndex);
state.Back = GetButton(Button.Back, controlIndex); state.B = GetButton(Button.B, controlIndex);
state.Y = GetButton(Button.Y, controlIndex);
state.X = GetButton(Button.X, controlIndex);
state.LeftStickAxis = GetAxis(Axis.LeftStick, controlIndex, raw); state.RightShoulder = GetButton(Button.RightShoulder, controlIndex);
state.rightStickAxis = GetAxis(Axis.RightStick, controlIndex, raw); state.LeftShoulder = GetButton(Button.LeftShoulder, controlIndex);
state.dPadAxis = GetAxis(Axis.Dpad, controlIndex, raw); state.RightStick = GetButton(Button.RightStick, controlIndex);
state.LeftStick = GetButton(Button.LeftStick, controlIndex);
state.Left = (state.dPadAxis.x < 0); state.Start = GetButton(Button.Start, controlIndex);
state.Right = (state.dPadAxis.x > 0); state.Back = GetButton(Button.Back, controlIndex);
state.Up = (state.dPadAxis.y > 0);
state.Down = (state.dPadAxis.y < 0);
state.LeftTrigger = GetTrigger(Trigger.LeftTrigger, controlIndex, raw); state.LeftStickAxis = GetAxis(Axis.LeftStick, controlIndex, raw);
state.RightTrigger = GetTrigger(Trigger.RightTrigger, controlIndex, raw); state.rightStickAxis = GetAxis(Axis.RightStick, controlIndex, raw);
state.dPadAxis = GetAxis(Axis.Dpad, controlIndex, raw);
return state; state.Left = (state.dPadAxis.x < 0);
} state.Right = (state.dPadAxis.x > 0);
state.Up = (state.dPadAxis.y > 0);
state.Down = (state.dPadAxis.y < 0);
state.LeftTrigger = GetTrigger(Trigger.LeftTrigger, controlIndex, raw);
state.RightTrigger = GetTrigger(Trigger.RightTrigger, controlIndex, raw);
return state;
} }
public class GamepadState }
{
public bool A = false;
public bool B = false;
public bool X = false;
public bool Y = false;
public bool Start = false;
public bool Back = false;
public bool Left = false;
public bool Right = false;
public bool Up = false;
public bool Down = false;
public bool LeftStick = false;
public bool RightStick = false;
public bool RightShoulder = false;
public bool LeftShoulder = false;
public Vector2 LeftStickAxis = Vector2.zero; public class GamepadState
public Vector2 rightStickAxis = Vector2.zero; {
public Vector2 dPadAxis = Vector2.zero; public bool A = false;
public bool B = false;
public bool X = false;
public bool Y = false;
public bool Start = false;
public bool Back = false;
public bool Left = false;
public bool Right = false;
public bool Up = false;
public bool Down = false;
public bool LeftStick = false;
public bool RightStick = false;
public bool RightShoulder = false;
public bool LeftShoulder = false;
public float LeftTrigger = 0; public Vector2 LeftStickAxis = Vector2.zero;
public float RightTrigger = 0; public Vector2 rightStickAxis = Vector2.zero;
public Vector2 dPadAxis = Vector2.zero;
} public float LeftTrigger = 0;
public float RightTrigger = 0;
}
} }
\ No newline at end of file
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class Bullet : MonoBehaviour { public class Bullet : MonoBehaviour
{
public int healingPoints = 10; public int healingPoints = 10;
public bool destroyTrap = false; public bool destroyTrap = false;
public int speed = 5; public int speed = 5;
/// <summary> /// <summary>
/// Das aufrufen, wenn die Kugel wirklich losgeschossen werden soll. /// Das aufrufen, wenn die Kugel wirklich losgeschossen werden soll.
/// </summary> /// </summary>
/// <param name="direction"></param> /// <param name="direction"></param>
public void shoot(Vector2 direction) public void shoot(Vector2 direction)
{
GetComponent<Rigidbody2D>().velocity = (float)speed * direction.normalized;
}
void OnTriggerEnter2D(Collider2D other)
{
//Debug.Log("Bullet colide with " + other.name);
if (healingPoints > 0 && other.tag == "Player")
{ {
GetComponent<Rigidbody2D>().velocity = (float)speed*direction.normalized; other.GetComponent<PlayerHealth>().changeHealthBy(healingPoints);
Destroy(gameObject);
} }
else if (destroyTrap && other.tag == "Trap")
void OnTriggerEnter2D(Collider2D other)
{ {
//Debug.Log("Bullet colide with " + other.name); other.GetComponent<Trap>().destroyTrap();
if (healingPoints > 0 && other.tag == "Player") Destroy(gameObject);
{
other.GetComponent<PlayerHealth>().changeHealthBy(healingPoints);
Destroy(gameObject);
}
else if (destroyTrap && other.tag == "Trap")
{
other.GetComponent<Trap>().destroyTrap();
Destroy(gameObject);
}
} }
}
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class FireScript : MonoBehaviour { public class FireScript : MonoBehaviour
{
PlayerHealth parentHealth; PlayerHealth parentHealth;
public float constantDamagepoints = 0.1f; public float constantDamagepoints = 0.1f;
public float burningTime = 10f; public float burningTime = 10f;
private Vector3 startScale; //fixes a bug: scale of fire was 0 when attached to the player. private Vector3 startScale; //fixes a bug: scale of fire was 0 when attached to the player.
void Start() void Start()
{ {
startScale = transform.localScale; startScale = transform.localScale;
} }
// Update is called once per frame
void Update () {
if (parentHealth)
{
parentHealth.changeHealthBy(-constantDamagepoints * Time.deltaTime);
}
}
void OnTriggerEnter2D(Collider2D other) // Update is called once per frame
void Update()
{
if (parentHealth)
{ {
if (other.tag == "Player") parentHealth.changeHealthBy(-constantDamagepoints * Time.deltaTime);
{
parentHealth = other.GetComponent<PlayerHealth>();
transform.position = other.transform.position; //hier schon position setzen
transform.parent = other.transform;
transform.localScale = startScale;
Invoke("stopBurning", burningTime);
}
} }
}
void stopBurning() void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{ {
Destroy(gameObject); parentHealth = other.GetComponent<PlayerHealth>();
transform.position = other.transform.position; //hier schon position setzen
transform.parent = other.transform;
transform.localScale = startScale;
Invoke("stopBurning", burningTime);
} }
}
void stopBurning()
{
Destroy(gameObject);
}
} }
...@@ -3,91 +3,93 @@ using System.Collections; ...@@ -3,91 +3,93 @@ using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine.UI; using UnityEngine.UI;
public class GameMaster : MonoBehaviour { public class GameMaster : MonoBehaviour
{
DeserializedLevelsLoader levelLoader; DeserializedLevelsLoader levelLoader;
public PlayerControl[] playerPrefabs; public PlayerControl[] playerPrefabs;
public GameObject gameOverPanel; public GameObject gameOverPanel;
public Text rankingText; public Text rankingText;
// Use this for initialization // Use this for initialization
void Start () { void Start()
levelLoader = new DeserializedLevelsLoader(); {
levelLoader.load(); levelLoader = new DeserializedLevelsLoader();
} levelLoader.load();
}
public void loadLevel(int numberOfPlayers, int level = -1) public void loadLevel(int numberOfPlayers, int level = -1)
{ {
if (level < 0) if (level < 0)
level = Random.Range(0, levelLoader.getLevelCount()); level = Random.Range(0, levelLoader.getLevelCount());
levelLoader.loadLevel(level); levelLoader.loadLevel(level);
deleteAllPlayers();
spawnPlayers(numberOfPlayers);
}
deleteAllPlayers();
spawnPlayers(numberOfPlayers);
}
private void deleteAllPlayers()
{
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Player"))
Object.Destroy(player, 0f);
}
private void deleteAllPlayers() private void spawnPlayers(int count)
{
Debug.Log("spawning " + count + " players");
GameObject[] startPositions = GameObject.FindGameObjectsWithTag("Start_Position");
if (count > startPositions.Length)
{ {
foreach (GameObject player in GameObject.FindGameObjectsWithTag("Player")) count = startPositions.Length;
Object.Destroy(player, 0f); Debug.LogError("map is capped at " + count + " players");
} }
private void spawnPlayers(int count) shuffle(startPositions);
for (int i = 0; i < count; i++)
{ {
Debug.Log("spawning " + count + " players"); PlayerControl player = (PlayerControl)Object.Instantiate(
playerPrefabs[i % playerPrefabs.Length],
startPositions[i].transform.position,
Quaternion.identity);
player.init(i + 1);
}
}
GameObject[] startPositions = GameObject.FindGameObjectsWithTag("Start_Position"); private static void shuffle<T>(T[] array)
if (count > startPositions.Length) {
{ int i = array.Length;
count = startPositions.Length; while (i > 1)
Debug.LogError("map is capped at " + count + " players"); {
} int k = Random.Range(0, i--);
T t = array[k];
array[k] = array[i];
array[i] = t;
}
}
shuffle(startPositions); public void gameOver(List<string> ranking)
{
gameOverPanel.SetActive(true);
for (int i = 0; i < count; i++) Debug.Log(ranking.Count);
{ if (ranking.Count > 0)
PlayerControl player = (PlayerControl) Object.Instantiate( {
playerPrefabs[i % playerPrefabs.Length], rankingText.text = "1st: " + ranking[0];
startPositions[i].transform.position,
Quaternion.identity);
player.init(i + 1);
}
} }
if (ranking.Count > 1)
private static void shuffle<T>(T[] array)
{ {
int i = array.Length; rankingText.text += "\n2nd: " + ranking[1];
while (i > 1)
{
int k = Random.Range(0, i--);
T t = array[k];
array[k] = array[i];
array[i] = t;
}
} }
if (ranking.Count > 2)
public void gameOver(List<string> ranking)
{ {
gameOverPanel.SetActive(true); rankingText.text += "\n3rd: " + ranking[2];
}
Debug.Log(ranking.Count); if (ranking.Count > 3)
if (ranking.Count > 0) {
{ rankingText.text += "\n4th: " + ranking[3];
rankingText.text = "1st: " + ranking[0];
}
if (ranking.Count > 1)
{
rankingText.text += "\n2nd: " + ranking[1];
}
if (ranking.Count > 2)
{
rankingText.text += "\n3rd: " + ranking[2];
}
if (ranking.Count > 3)
{
rankingText.text += "\n4th: " + ranking[3];
}
} }
}
} }
...@@ -2,72 +2,74 @@ ...@@ -2,72 +2,74 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
public class GameStateTracker : MonoBehaviour { public class GameStateTracker : MonoBehaviour
{
private int numberOfPlayers; private int numberOfPlayers;
/// <summary> /// <summary>
/// Numbers of Player ranked 4th to winner /// Numbers of Player ranked 4th to winner
/// </summary> /// </summary>
private int fourthPlayer; private int fourthPlayer;
private int thirdPlayer; private int thirdPlayer;
private int secondPlayer; private int secondPlayer;
private int winnerPlayer; private int winnerPlayer;
private List<string> ranking; private List<string> ranking;
private GameMaster gameMaster; private GameMaster gameMaster;
void Awake() void Awake()
{ {
ranking = new List<string>(); ranking = new List<string>();
} }
// Use this for initialization // Use this for initialization
void Start () { void Start()
gameMaster = GetComponent<GameMaster>(); {
} gameMaster = GetComponent<GameMaster>();
}
public void reset()
{
ranking.Clear();
}
public void setNumberOfPlayers(int players)
{
numberOfPlayers = players;
}
public void reset() public void playerDied(string name)
{
if (!ranking.Contains(name))
{ {
ranking.Clear(); ranking.Add(name);
} }
if (ranking.Count >= numberOfPlayers - 1)
public void setNumberOfPlayers(int players)
{ {
numberOfPlayers = players; gameOver();
} }
}
public void playerDied(string name) public void gameOver()
{ {
if (!ranking.Contains(name)) Time.timeScale = 0.0f; //stops the game
{
ranking.Add(name);
}
if (ranking.Count >= numberOfPlayers - 1)
{
gameOver();
}
}
public void gameOver() //find the player who is still alive:
string playerStillAlive = "";
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject p in players)
{ {
Time.timeScale = 0.0f; //stops the game if (p.GetComponent<PlayerHealth>().getCurrentHealth() > 0)
{
//find the player who is still alive: playerStillAlive = p.name;
string playerStillAlive = ""; ranking.Add(playerStillAlive);
GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); break;
foreach (GameObject p in players) }
{
if (p.GetComponent<PlayerHealth>().getCurrentHealth() > 0)
{
playerStillAlive = p.name;
ranking.Add(playerStillAlive);
break;
}
}
gameMaster.gameOver(ranking); //shows the game over screen
} }
gameMaster.gameOver(ranking); //shows the game over screen
}
} }
...@@ -6,11 +6,12 @@ using System.IO; ...@@ -6,11 +6,12 @@ using System.IO;
using System.Xml; using System.Xml;
using System.Linq; using System.Linq;
public class DeserializedLevelsCrossChecker { public class DeserializedLevelsCrossChecker
{
//Hallo Tim und Philipp. Die Datei kuckt nur ob irgendwas mit den Prefabs komisch ist. //Hallo Tim und Philipp. Die Datei kuckt nur ob irgendwas mit den Prefabs komisch ist.
// cross check /Resources/Prefabs and Levels.xml if there are any item prefabs that exist only in one but not the other // cross check /Resources/Prefabs and Levels.xml if there are any item prefabs that exist only in one but not the other
public void crossCheck () public void crossCheck()
{ {
// create a list of /Resources/Prefabs for resources and Levels.Xml // create a list of /Resources/Prefabs for resources and Levels.Xml
List<string> resPrefabList = new List<string>(); List<string> resPrefabList = new List<string>();
...@@ -33,16 +34,16 @@ public class DeserializedLevelsCrossChecker { ...@@ -33,16 +34,16 @@ public class DeserializedLevelsCrossChecker {
fileInfos.Select(f => f.FullName).ToArray(); fileInfos.Select(f => f.FullName).ToArray();
// Add each prefab's file name to prefabList and truncate the .prefab extension from the end // Add each prefab's file name to prefabList and truncate the .prefab extension from the end
foreach (FileInfo fileInfo in fileInfos) foreach (FileInfo fileInfo in fileInfos)
resPrefabList.Add (fileInfo.Name.Substring(0, fileInfo.Name.Length - ".prefab".Length)); resPrefabList.Add(fileInfo.Name.Substring(0, fileInfo.Name.Length - ".prefab".Length));
// Cross checks // Cross checks
foreach (string prefab in xmlPrefabList.Except(resPrefabList).ToList()) foreach (string prefab in xmlPrefabList.Except(resPrefabList).ToList())
Debug.LogError (prefab + " is missing in the /Resorces/Prefabs folder but used in Levels.xml"); Debug.LogError(prefab + " is missing in the /Resorces/Prefabs folder but used in Levels.xml");
foreach (string prefab in resPrefabList.Except(xmlPrefabList).ToList()) foreach (string prefab in resPrefabList.Except(xmlPrefabList).ToList())
Debug.Log (prefab + " exists in the /Resorces/Prefabs folder but not used in Levels.xml"); Debug.Log(prefab + " exists in the /Resorces/Prefabs folder but not used in Levels.xml");
Debug.Log ("Cross Check Done"); Debug.Log("Cross Check Done");
} }
} }
...@@ -24,17 +24,17 @@ public class DeserializedLevelsLoader ...@@ -24,17 +24,17 @@ public class DeserializedLevelsLoader
struct ItemChildStruct struct ItemChildStruct
{ {
public string name; public string name;
public float x; public float x;
public float y; public float y;
public float rot; public float rot;
public float scalex; public float scalex;
public float scaley; public float scaley;
} }
// Cache prefabs in prefabDict // Cache prefabs in prefabDict
Dictionary<string,GameObject> prefabPool; Dictionary<string, GameObject> prefabPool;
// Cache all items with locations // Cache all items with locations
List<ItemStruct> sceneItemsList; List<ItemStruct> sceneItemsList;
...@@ -43,12 +43,12 @@ public class DeserializedLevelsLoader ...@@ -43,12 +43,12 @@ public class DeserializedLevelsLoader
public const string xmlItemsGOName = "XmlItems"; public const string xmlItemsGOName = "XmlItems";
public void load () public void load()
{ {
deserializedLevels = XmlIO.LoadXml<DeserializedLevels>("Levels"); deserializedLevels = XmlIO.LoadXml<DeserializedLevels>("Levels");
} }
public int getLevelCount () public int getLevelCount()
{ {
if (deserializedLevels == null) if (deserializedLevels == null)
throw new System.InvalidOperationException(); throw new System.InvalidOperationException();
...@@ -56,7 +56,7 @@ public class DeserializedLevelsLoader ...@@ -56,7 +56,7 @@ public class DeserializedLevelsLoader
return deserializedLevels.levels.Length; return deserializedLevels.levels.Length;
} }
public void loadLevel (int levelIndex = 0) public void loadLevel(int levelIndex = 0)
{ {
if (deserializedLevels == null) if (deserializedLevels == null)
throw new System.InvalidOperationException(); throw new System.InvalidOperationException();
...@@ -68,8 +68,8 @@ public class DeserializedLevelsLoader ...@@ -68,8 +68,8 @@ public class DeserializedLevelsLoader
sceneItemsList = new List<ItemStruct>(); sceneItemsList = new List<ItemStruct>();
// if the XmlItems gameobject folder remained in the Hierarcy, then delete it // if the XmlItems gameobject folder remained in the Hierarcy, then delete it
while (GameObject.Find (xmlItemsGOName) != null) while (GameObject.Find(xmlItemsGOName) != null)
MonoBehaviour.DestroyImmediate(GameObject.Find (xmlItemsGOName)); MonoBehaviour.DestroyImmediate(GameObject.Find(xmlItemsGOName));
parentOfXmlItems = new GameObject(xmlItemsGOName).transform; parentOfXmlItems = new GameObject(xmlItemsGOName).transform;
...@@ -116,12 +116,12 @@ public class DeserializedLevelsLoader ...@@ -116,12 +116,12 @@ public class DeserializedLevelsLoader
int k = 0; int k = 0;
foreach (DeserializedLevels.Item child in children) foreach (DeserializedLevels.Item child in children)
{ {
item.children[k].name = child.prefab; item.children[k].name = child.prefab;
item.children[k].x = toFloatZeroIfNull(child.x); item.children[k].x = toFloatZeroIfNull(child.x);
item.children[k].y = toFloatZeroIfNull(child.y); item.children[k].y = toFloatZeroIfNull(child.y);
item.children[k].rot = toFloatZeroIfNull(child.rot); item.children[k].rot = toFloatZeroIfNull(child.rot);
item.children[k].scalex = toFloatOneIfNull(child.scalex); item.children[k].scalex = toFloatOneIfNull(child.scalex);
item.children[k].scaley = toFloatOneIfNull(child.scaley); item.children[k].scaley = toFloatOneIfNull(child.scaley);
} }
sceneItemsList.Add(item); sceneItemsList.Add(item);
...@@ -144,19 +144,19 @@ public class DeserializedLevelsLoader ...@@ -144,19 +144,19 @@ public class DeserializedLevelsLoader
foreach (Transform t in newGameObject.GetComponentsInChildren<Transform>()) foreach (Transform t in newGameObject.GetComponentsInChildren<Transform>())
{ {
if (!(t.parent == null) && (!t.parent.name.Equals("XmlItems"))) if (!(t.parent == null) && (!t.parent.name.Equals("XmlItems")))
{
foreach (ItemChildStruct child in item.children) //Ja das ist wahrscheinlich Laufzeitmig nicht ideal, aber die Arrays haben eh nur eine Hand viele Elemente
{ {
foreach (ItemChildStruct child in item.children) //Ja das ist wahrscheinlich Laufzeitmig nicht ideal, aber die Arrays haben eh nur eine Hand viele Elemente if (t.name == child.name)
{ {
if (t.name == child.name) Debug.Log("Set child " + child.name);
{ setPos2D(t.gameObject, new Vector2(child.x, child.y));
Debug.Log("Set child " + child.name); setRot2D(t.gameObject, child.rot);
setPos2D(t.gameObject, new Vector2(child.x, child.y)); setScale2D(t.gameObject, child.scalex, child.scaley);
setRot2D(t.gameObject, child.rot); }
setScale2D(t.gameObject, child.scalex, child.scaley);
}
}
} }
}
} }
// set parent // set parent
newGameObject.transform.parent = parentOfXmlItems; newGameObject.transform.parent = parentOfXmlItems;
...@@ -167,12 +167,12 @@ public class DeserializedLevelsLoader ...@@ -167,12 +167,12 @@ public class DeserializedLevelsLoader
// DONE, these are only helper functions below // DONE, these are only helper functions below
// if no value then return zero or one, otherwise convert to float // if no value then return zero or one, otherwise convert to float
float toFloatZeroIfNull (string value) { return value == null ? 0 : float.Parse(value); } float toFloatZeroIfNull(string value) { return value == null ? 0 : float.Parse(value); }
float toFloatOneIfNull (string value) { return value == null ? 1 : float.Parse(value); } float toFloatOneIfNull(string value) { return value == null ? 1 : float.Parse(value); }
void setPos2D(GameObject g, Vector2 pos) void setPos2D(GameObject g, Vector2 pos)
{ {
g.transform.position = new Vector2 ( g.transform.position = new Vector2(
pos.x, pos.x,
pos.y pos.y
); );
......
...@@ -6,19 +6,19 @@ public class DeserializedLevelsSaver ...@@ -6,19 +6,19 @@ public class DeserializedLevelsSaver
{ {
public const string xmlItemsToExportGOName = "XmlItemsToExport"; public const string xmlItemsToExportGOName = "XmlItemsToExport";
public void saveExportItems () public void saveExportItems()
{ {
// Create XmlItemsToExport if does not exist yet // Create XmlItemsToExport if does not exist yet
if (GameObject.Find (xmlItemsToExportGOName) == null) if (GameObject.Find(xmlItemsToExportGOName) == null)
new GameObject(xmlItemsToExportGOName); new GameObject(xmlItemsToExportGOName);
GameObject xmlItemsToExportGO = GameObject.Find (xmlItemsToExportGOName); GameObject xmlItemsToExportGO = GameObject.Find(xmlItemsToExportGOName);
var xmlItemsToExportGOchildren = xmlItemsToExportGO.GetComponentsInChildren<Transform>(); var xmlItemsToExportGOchildren = xmlItemsToExportGO.GetComponentsInChildren<Transform>();
// Check if any children exist // Check if any children exist
if (xmlItemsToExportGOchildren.Length == 0) if (xmlItemsToExportGOchildren.Length == 0)
Debug.LogError ("Add the prefabs to " + xmlItemsToExportGOName); Debug.LogError("Add the prefabs to " + xmlItemsToExportGOName);
DeserializedLevels.Level levelXml = new DeserializedLevels.Level(); DeserializedLevels.Level levelXml = new DeserializedLevels.Level();
...@@ -55,28 +55,28 @@ public class DeserializedLevelsSaver ...@@ -55,28 +55,28 @@ public class DeserializedLevelsSaver
int k = 0; int k = 0;
foreach (Transform t in item.GetComponentsInChildren<Transform>()) foreach (Transform t in item.GetComponentsInChildren<Transform>())
{ {
if (!t.parent.name.Equals("XmlItemsToExport")) if (!t.parent.name.Equals("XmlItemsToExport"))
{ {
//GetComponentsInChildren gibt auch die Komponente aus dem Parent (also dem Objekt selbst) zurck //GetComponentsInChildren gibt auch die Komponente aus dem Parent (also dem Objekt selbst) zurck
DeserializedLevels.Item child = new DeserializedLevels.Item(); DeserializedLevels.Item child = new DeserializedLevels.Item();
Debug.Log("Add child " + t.name); Debug.Log("Add child " + t.name);
child.prefab = t.name; child.prefab = t.name;
child.x = toStringNullIfZero(t.position.x); child.x = toStringNullIfZero(t.position.x);
child.y = toStringNullIfZero(t.position.y); child.y = toStringNullIfZero(t.position.y);
child.rot = toStringNullIfZero(t.rotation.eulerAngles.z); child.rot = toStringNullIfZero(t.rotation.eulerAngles.z);
child.scalex = toStringNullIfOne(t.localScale.x); child.scalex = toStringNullIfOne(t.localScale.x);
child.scaley = toStringNullIfOne(t.localScale.y); child.scaley = toStringNullIfOne(t.localScale.y);
children[k] = child; children[k] = child;
k++; k++;
} }
} }
levelXml.items[i].children = (item.childCount > 0) ? children : null; levelXml.items[i].children = (item.childCount > 0) ? children : null;
i++; i++;
} }
...@@ -87,12 +87,12 @@ public class DeserializedLevelsSaver ...@@ -87,12 +87,12 @@ public class DeserializedLevelsSaver
XmlIO.SaveXml<DeserializedLevels>(levelsXmlToExport, "./Assets/Resources/" + xmlItemsToExportGOName + ".xml"); XmlIO.SaveXml<DeserializedLevels>(levelsXmlToExport, "./Assets/Resources/" + xmlItemsToExportGOName + ".xml");
} }
string toStringNullIfZero (float num) { return num == 0 ? null : mathRound(num,2).ToString(); } string toStringNullIfZero(float num) { return num == 0 ? null : mathRound(num, 2).ToString(); }
string toStringNullIfOne (float num) { return num == 1 ? null : mathRound(num,2).ToString(); } string toStringNullIfOne(float num) { return num == 1 ? null : mathRound(num, 2).ToString(); }
float mathRound (float round, int decimals) float mathRound(float round, int decimals)
{ {
return Mathf.Round(round * Mathf.Pow(10,decimals)) / Mathf.Pow(10,decimals); return Mathf.Round(round * Mathf.Pow(10, decimals)) / Mathf.Pow(10, decimals);
} }
} }
...@@ -5,9 +5,9 @@ using UnityEngine; // necessary for TextAsset ...@@ -5,9 +5,9 @@ using UnityEngine; // necessary for TextAsset
public static class XmlIO public static class XmlIO
{ {
public static void SaveXml<T> (this object deserializedXml, string path) where T : class public static void SaveXml<T>(this object deserializedXml, string path) where T : class
{ {
using(var stream = new FileStream(path, FileMode.Create)) using (var stream = new FileStream(path, FileMode.Create))
{ {
var s = new XmlSerializer(typeof(T)); var s = new XmlSerializer(typeof(T));
s.Serialize(stream, deserializedXml); s.Serialize(stream, deserializedXml);
...@@ -16,9 +16,9 @@ public static class XmlIO ...@@ -16,9 +16,9 @@ public static class XmlIO
public static T LoadXml<T>(string textAssetName) where T : class public static T LoadXml<T>(string textAssetName) where T : class
{ {
TextAsset xmlTextAsset = (TextAsset) Resources.Load (textAssetName, typeof(TextAsset)); TextAsset xmlTextAsset = (TextAsset)Resources.Load(textAssetName, typeof(TextAsset));
using(var stream = new StringReader(xmlTextAsset.text)) using (var stream = new StringReader(xmlTextAsset.text))
{ {
var s = new XmlSerializer(typeof(T)); var s = new XmlSerializer(typeof(T));
T deserializedXml = s.Deserialize(stream) as T; T deserializedXml = s.Deserialize(stream) as T;
......
...@@ -6,208 +6,208 @@ using UnityEngine.UI; ...@@ -6,208 +6,208 @@ using UnityEngine.UI;
public class Menu : MonoBehaviour public class Menu : MonoBehaviour
{ {
public GameStateTracker gameStateTracker; public GameStateTracker gameStateTracker;
public GameObject gameUI; public GameObject gameUI;
public GameMaster gameMaster; public GameMaster gameMaster;
public GameObject menuPanel; public GameObject menuPanel;
public GameObject p1Image, p2Image, p3Image, p4Image; public GameObject p1Image, p2Image, p3Image, p4Image;
public List<PlayerInputMapping> inputMappings; public List<PlayerInputMapping> inputMappings;
private int numberOfRegisteredPlayers; private int numberOfRegisteredPlayers;
private bool WASDAdded, ArrowAdded, GP1Added, GP2Added, GP3Added, GP4Added; private bool WASDAdded, ArrowAdded, GP1Added, GP2Added, GP3Added, GP4Added;
void Start() void Start()
{
#region init bools
WASDAdded = false;
ArrowAdded = false;
GP1Added = false;
GP2Added = false;
GP3Added = false;
GP4Added = false;
#endregion
numberOfRegisteredPlayers = 0;
inputMappings = new List<PlayerInputMapping>();
for (int i = 1; i < 5; i++)
{ {
#region init bools inputMappings.Add(GameObject.Find("InputMapping" + i).GetComponent<PlayerInputMapping>());
WASDAdded = false; }
ArrowAdded = false; }
GP1Added = false;
GP2Added = false; //returns true if game was started;
GP3Added = false; private bool startGameIfPossible(int levelNumber = -1)
GP4Added = false; {
#endregion if (numberOfRegisteredPlayers > 1 || (numberOfRegisteredPlayers > 0 && Debug.isDebugBuild))
numberOfRegisteredPlayers = 0; {
inputMappings = new List<PlayerInputMapping>(); gameUI.SetActive(true);
for (int i = 1; i < 5; i++) gameStateTracker.setNumberOfPlayers(numberOfRegisteredPlayers);
{ gameStateTracker.reset();
inputMappings.Add(GameObject.Find("InputMapping" + i).GetComponent<PlayerInputMapping>()); gameMaster.loadLevel(numberOfRegisteredPlayers, levelNumber);
} gameObject.SetActive(false);
return true;
} }
else return false;
}
//returns true if game was started; void Update()
private bool startGameIfPossible(int levelNumber = -1) {
if (Debug.isDebugBuild)
{ {
if (numberOfRegisteredPlayers > 1 || (numberOfRegisteredPlayers > 0 && Debug.isDebugBuild)) for (int i = 0; i < 10; i++)
{
if (Input.GetKeyDown(i.ToString()))
{ {
gameUI.SetActive(true); startGameIfPossible(i);
gameStateTracker.setNumberOfPlayers(numberOfRegisteredPlayers);
gameStateTracker.reset();
gameMaster.loadLevel(numberOfRegisteredPlayers, levelNumber);
gameObject.SetActive(false);
return true;
} }
else return false; }
} }
void Update() if (Input.GetKeyDown(KeyCode.Space))
{ {
if (Debug.isDebugBuild) if (WASDAdded)
{
if (startGameIfPossible())
{ {
for (int i = 0; i < 10; i++) return;
{
if (Input.GetKeyDown(i.ToString()))
{
startGameIfPossible(i);
}
}
} }
}
if (Input.GetKeyDown(KeyCode.Space)) else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
if (WASDAdded) inputMappings[playerNumber - 1].set(controlType.WASD);
{ WASDAdded = true;
if (startGameIfPossible())
{
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
inputMappings[playerNumber-1].set(controlType.WASD);
WASDAdded = true;
}
}
} }
if (Input.GetKeyDown(KeyCode.RightControl)) }
}
if (Input.GetKeyDown(KeyCode.RightControl))
{
if (ArrowAdded)
{
if (startGameIfPossible())
{ {
if (ArrowAdded) return;
{
if (startGameIfPossible())
{
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
ArrowAdded = true;
inputMappings[playerNumber-1].set(controlType.ARROWS);
}
}
} }
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.One)) }
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
if (GP1Added) ArrowAdded = true;
{ inputMappings[playerNumber - 1].set(controlType.ARROWS);
if (startGameIfPossible()) }
{ }
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
GP1Added = true;
inputMappings[playerNumber-1].set(controlType.GAMEPAD1);
}
}
}
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.One))
{
if (GP1Added)
{
if (startGameIfPossible())
{
return;
} }
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Two)) }
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
if (GP2Added) GP1Added = true;
{ inputMappings[playerNumber - 1].set(controlType.GAMEPAD1);
if (startGameIfPossible())
{
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
GP2Added = true;
inputMappings[playerNumber-1].set(controlType.GAMEPAD2);
}
}
} }
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Three)) }
}
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Two))
{
if (GP2Added)
{
if (startGameIfPossible())
{ {
if (GP3Added) return;
{
if (startGameIfPossible())
{
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
GP3Added = true;
inputMappings[playerNumber-1].set(controlType.GAMEPAD3);
}
}
} }
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Four)) }
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
if (GP4Added) GP2Added = true;
{ inputMappings[playerNumber - 1].set(controlType.GAMEPAD2);
if (startGameIfPossible())
{
return;
}
}
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{
GP4Added = true;
inputMappings[playerNumber-1].set(controlType.GAMEPAD4);
}
}
} }
} }
//returns the player number (3 for player three). returns -1 when there is no free player slot. }
private int addPlayer() if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Three))
{ {
if (!p1Image.activeSelf) if (GP3Added)
{
if (startGameIfPossible())
{ {
p1Image.SetActive(true); return;
numberOfRegisteredPlayers = 1;
return 1;
} }
else if (!p2Image.activeSelf) }
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
p2Image.SetActive(true); GP3Added = true;
numberOfRegisteredPlayers = 2; inputMappings[playerNumber - 1].set(controlType.GAMEPAD3);
return 2;
} }
else if (!p3Image.activeSelf) }
}
if (GamePad.GetButtonDown(GamePad.Button.A, GamePad.Index.Four))
{
if (GP4Added)
{
if (startGameIfPossible())
{ {
p3Image.SetActive(true); return;
numberOfRegisteredPlayers = 3;
return 3;
} }
else if (!p4Image.activeSelf) }
else
{
int playerNumber = addPlayer();
if (playerNumber > 0)
{ {
p4Image.SetActive(true); GP4Added = true;
numberOfRegisteredPlayers = 4; inputMappings[playerNumber - 1].set(controlType.GAMEPAD4);
return 4;
} }
else return -1; }
}
}
//returns the player number (3 for player three). returns -1 when there is no free player slot.
private int addPlayer()
{
if (!p1Image.activeSelf)
{
p1Image.SetActive(true);
numberOfRegisteredPlayers = 1;
return 1;
}
else if (!p2Image.activeSelf)
{
p2Image.SetActive(true);
numberOfRegisteredPlayers = 2;
return 2;
}
else if (!p3Image.activeSelf)
{
p3Image.SetActive(true);
numberOfRegisteredPlayers = 3;
return 3;
}
else if (!p4Image.activeSelf)
{
p4Image.SetActive(true);
numberOfRegisteredPlayers = 4;
return 4;
} }
else return -1;
}
} }
...@@ -5,286 +5,286 @@ using GamepadInput; ...@@ -5,286 +5,286 @@ using GamepadInput;
public class PlayerControl : MonoBehaviour public class PlayerControl : MonoBehaviour
{ {
private Rigidbody2D body2D; private Rigidbody2D body2D;
public Transform groundCheck; public Transform groundCheck;
public LayerMask mask; public LayerMask mask;
// movement config // movement config
public float pushForce = 5f; public float pushForce = 5f;
public float pushTime = 0.5f; public float pushTime = 0.5f;
public float gravity = -15f; public float gravity = -15f;
public float runSpeed = 8f; public float runSpeed = 8f;
public float groundDamping = 20f; // how fast do we change direction? higher means faster public float groundDamping = 20f; // how fast do we change direction? higher means faster
public float inAirDamping = 5f; //only horizontal public float inAirDamping = 5f; //only horizontal
public float inAirDampingVertical = 10f; public float inAirDampingVertical = 10f;
public float targetJumpHeight = 2f; public float targetJumpHeight = 2f;
public float lastDashStart = float.NegativeInfinity; public float lastDashStart = float.NegativeInfinity;
[HideInInspector] [HideInInspector]
public Vector2 dashDirection = Vector2.right; public Vector2 dashDirection = Vector2.right;
[HideInInspector] [HideInInspector]
public Vector2 currentDashDirection = Vector2.right; public Vector2 currentDashDirection = Vector2.right;
public float dashCompletionTime = 0.25f; public float dashCompletionTime = 0.25f;
public float dashStartSpeed = 20.0f; public float dashStartSpeed = 20.0f;
public float dashEndSpeed = 8.0f; public float dashEndSpeed = 8.0f;
public float dashCoolDown = 0.4f; public float dashCoolDown = 0.4f;
public float dashVerticalScale = 0.5f; public float dashVerticalScale = 0.5f;
public float dashCollisionCoolDown = 1.5f; public float dashCollisionCoolDown = 1.5f;
[HideInInspector] [HideInInspector]
public float currentDashCoolDown = 0.0f; public float currentDashCoolDown = 0.0f;
[HideInInspector] [HideInInspector]
public bool hasLandedSinceLastDash = true; public bool hasLandedSinceLastDash = true;
// public float jumpWaitTime = 2.0; // public float jumpWaitTime = 2.0;
[HideInInspector] [HideInInspector]
public Vector2 pushSpeed = Vector2.zero; public Vector2 pushSpeed = Vector2.zero;
[HideInInspector] [HideInInspector]
public float lastPushStart = float.NegativeInfinity; public float lastPushStart = float.NegativeInfinity;
[HideInInspector] [HideInInspector]
public float rawMovementDirection = 1; public float rawMovementDirection = 1;
//[HideInInspector] //[HideInInspector]
public float normalizedHorizontalSpeed = 0; public float normalizedHorizontalSpeed = 0;
[HideInInspector] [HideInInspector]
public Vector2 velocity; public Vector2 velocity;
public int playerNumber = 1; //gibt an, ob es sich um player one, player two, etc. handelt. sollte nicht 0 sein; public int playerNumber = 1; //gibt an, ob es sich um player one, player two, etc. handelt. sollte nicht 0 sein;
public PlayerInputMapping inputMapping; public PlayerInputMapping inputMapping;
public Animator dashAnimator; public Animator dashAnimator;
void Start() void Start()
{
body2D = GetComponent<Rigidbody2D>();
}
public void init(int playerNumber)
{
this.playerNumber = playerNumber;
//in der szene muss fuer jeden spieer so ein InputMapping"nr" sein:
inputMapping = GameObject.Find("InputMapping" + playerNumber).GetComponent<PlayerInputMapping>();
GetComponent<PlayerHealth>().init(playerNumber);
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.collider.tag != "Player" || !isDashing())
return;
PlayerControl other = coll.collider.gameObject.GetComponent<PlayerControl>();
other.setPushSpeed(currentDashDirection * pushForce);
lastDashStart = Time.time - dashCompletionTime;
currentDashCoolDown = dashCollisionCoolDown;
//dash effect:
dashAnimator.SetTrigger("play");
}
private void setPushSpeed(Vector2 pushSpeed)
{
this.pushSpeed = pushSpeed;
this.lastPushStart = Time.time;
}
void FixedUpdate()
{
if (isGrounded())
velocity.y = 0;
updateDashDirection();
if (canDash() && inputMapping.isDashPressed())
{ {
body2D = GetComponent<Rigidbody2D>(); lastDashStart = Time.time;
currentDashDirection = dashDirection;
currentDashCoolDown = dashCoolDown;
hasLandedSinceLastDash = false;
} }
public void init(int playerNumber) if (isDashing())
{ {
this.playerNumber = playerNumber; velocity = currentDashDirection * Mathf.Lerp(dashStartSpeed, dashEndSpeed, getDashTime() / dashCompletionTime);
//in der szene muss fuer jeden spieer so ein InputMapping"nr" sein:
inputMapping = GameObject.Find("InputMapping" + playerNumber).GetComponent<PlayerInputMapping>();
GetComponent<PlayerHealth>().init(playerNumber);
} }
else
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.collider.tag != "Player" || !isDashing())
return;
PlayerControl other = coll.collider.gameObject.GetComponent<PlayerControl>();
other.setPushSpeed(currentDashDirection * pushForce);
lastDashStart = Time.time - dashCompletionTime;
currentDashCoolDown = dashCollisionCoolDown;
//dash effect:
dashAnimator.SetTrigger("play");
}
private void setPushSpeed(Vector2 pushSpeed)
{ {
this.pushSpeed = pushSpeed; bool grounded = isGrounded();
this.lastPushStart = Time.time; if (grounded && !isDashing())
} {
hasLandedSinceLastDash = true;
void FixedUpdate() }
{
if (isGrounded()) velocity = body2D.velocity;
velocity.y = 0; if (inputMapping.isRightPressed())
{
updateDashDirection(); if (transform.localScale.x > 0f)
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
if (canDash() && inputMapping.isDashPressed())
velocity.x = runSpeed;
}
else if (inputMapping.isLeftPressed())
{
if (transform.localScale.x < 0f)
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
velocity.x = -runSpeed;
}
if (inputMapping.isJumpPressed())
{
//to avoid DOUBLE JUMP
if (grounded)
{ {
lastDashStart = Time.time; velocity.y = targetJumpHeight;
currentDashDirection = dashDirection;
currentDashCoolDown = dashCoolDown;
hasLandedSinceLastDash = false;
} }
}
if (isDashing()) // apply horizontal speed smoothing it
{ var smoothedMovementFactor = isGrounded() ? groundDamping : inAirDamping; // how fast do we change direction?
velocity = currentDashDirection * Mathf.Lerp(dashStartSpeed, dashEndSpeed, getDashTime() / dashCompletionTime); velocity.x = Mathf.Lerp(velocity.x, 0, Time.deltaTime * smoothedMovementFactor);
}
else
{
bool grounded = isGrounded();
if (grounded && !isDashing())
{
hasLandedSinceLastDash = true;
}
velocity = body2D.velocity;
if (inputMapping.isRightPressed())
{
if (transform.localScale.x > 0f)
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
velocity.x = runSpeed;
}
else if (inputMapping.isLeftPressed())
{
if (transform.localScale.x < 0f)
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
velocity.x = -runSpeed;
}
if (inputMapping.isJumpPressed())
{
//to avoid DOUBLE JUMP
if (grounded)
{
velocity.y = targetJumpHeight;
}
}
// apply horizontal speed smoothing it
var smoothedMovementFactor = isGrounded() ? groundDamping : inAirDamping; // how fast do we change direction?
velocity.x = Mathf.Lerp(velocity.x, 0, Time.deltaTime * smoothedMovementFactor);
float verticalSmoothedFactor = isGrounded() ? 0 : inAirDampingVertical;
if (velocity.y > 0.0f) velocity.y = Mathf.Lerp(velocity.y, 0, Time.deltaTime * verticalSmoothedFactor);
/*==========Power Ups // Bullet management ===*/
if (inputMapping.isShootPressed())
{
Debug.Log("Shoot pressed. Can shoot: " + canShoot());
if (canShoot())
{
shoot();
coolDown();
}
}
}
float currentPushTime = Time.time - lastPushStart; float verticalSmoothedFactor = isGrounded() ? 0 : inAirDampingVertical;
Vector2 currentPushSpeed = Vector2.zero; if (velocity.y > 0.0f) velocity.y = Mathf.Lerp(velocity.y, 0, Time.deltaTime * verticalSmoothedFactor);
if (0 <= currentPushTime && currentPushTime <= pushTime)
{
currentPushSpeed = Vector2.Lerp(pushSpeed, Vector2.zero, currentPushTime / pushTime);
}
//finally set the velocity:
body2D.velocity = velocity + currentPushSpeed;
}
private bool isGrounded() /*==========Power Ups // Bullet management ===*/
{ if (inputMapping.isShootPressed())
Vector2 playerPos = new Vector2(transform.position.x, transform.position.y); {
Vector2 groundPos = new Vector2(groundCheck.position.x, groundCheck.position.y); Debug.Log("Shoot pressed. Can shoot: " + canShoot());
bool result = Physics2D.Linecast(playerPos, groundPos, mask); if (canShoot())
if (result)
{
Debug.DrawLine(playerPos, groundPos, Color.green, 0.5f, false);
}
else
{ {
Debug.DrawLine(playerPos, groundPos, Color.red, 0.5f, false); shoot();
coolDown();
} }
}
return result;
} }
private void updateDashDirection() float currentPushTime = Time.time - lastPushStart;
Vector2 currentPushSpeed = Vector2.zero;
if (0 <= currentPushTime && currentPushTime <= pushTime)
{ {
float horizontalDashDirection = 0.0f; currentPushSpeed = Vector2.Lerp(pushSpeed, Vector2.zero, currentPushTime / pushTime);
if (inputMapping.isRightPressed()) }
{
horizontalDashDirection = 1.0f;
}
else if (inputMapping.isLeftPressed())
{
horizontalDashDirection = -1.0f;
}
float verticalDashDirection = 0.0f; //finally set the velocity:
if (inputMapping.isUpPressed()) body2D.velocity = velocity + currentPushSpeed;
{ }
verticalDashDirection = 1.0f;
}
else if (inputMapping.isDownPressed())
{
verticalDashDirection = -1.0f;
}
if (horizontalDashDirection != 0.0f || verticalDashDirection != 0.0f) private bool isGrounded()
dashDirection = new Vector2(horizontalDashDirection, dashVerticalScale * verticalDashDirection); {
Vector2 playerPos = new Vector2(transform.position.x, transform.position.y);
Vector2 groundPos = new Vector2(groundCheck.position.x, groundCheck.position.y);
bool result = Physics2D.Linecast(playerPos, groundPos, mask);
if (result)
{
Debug.DrawLine(playerPos, groundPos, Color.green, 0.5f, false);
} }
else
private float getDashTime()
{ {
return Time.time - lastDashStart; Debug.DrawLine(playerPos, groundPos, Color.red, 0.5f, false);
} }
private bool isDashing() return result;
}
private void updateDashDirection()
{
float horizontalDashDirection = 0.0f;
if (inputMapping.isRightPressed())
{ {
float dashTime = getDashTime(); horizontalDashDirection = 1.0f;
return 0 <= dashTime && dashTime < dashCompletionTime; }
else if (inputMapping.isLeftPressed())
{
horizontalDashDirection = -1.0f;
} }
private bool canDash() float verticalDashDirection = 0.0f;
if (inputMapping.isUpPressed())
{ {
return hasLandedSinceLastDash && getDashTime() >= dashCompletionTime + currentDashCoolDown; verticalDashDirection = 1.0f;
}
else if (inputMapping.isDownPressed())
{
verticalDashDirection = -1.0f;
} }
/*==========Power Ups // Bullet management ===*/ if (horizontalDashDirection != 0.0f || verticalDashDirection != 0.0f)
dashDirection = new Vector2(horizontalDashDirection, dashVerticalScale * verticalDashDirection);
}
public const int POWERUP_NONE = 0; private float getDashTime()
public const int POWERUP_HEALINGBULLET = 1; {
public const int POWERUP_TRAPDESTROYER = 2; return Time.time - lastDashStart;
}
private int powerUpType = POWERUP_NONE; private bool isDashing()
{
float dashTime = getDashTime();
return 0 <= dashTime && dashTime < dashCompletionTime;
}
private bool coolingDown = false; private bool canDash()
{
return hasLandedSinceLastDash && getDashTime() >= dashCompletionTime + currentDashCoolDown;
}
public float coolDownTime = 2.0f; /*==========Power Ups // Bullet management ===*/
public GameObject healingBulletPrefab; public const int POWERUP_NONE = 0;
public GameObject trapDestroyingBulletPrefab; public const int POWERUP_HEALINGBULLET = 1;
public const int POWERUP_TRAPDESTROYER = 2;
public float spawnDistance = 1.0f; private int powerUpType = POWERUP_NONE;
public void setPowerUpType(int type)
{
powerUpType = type;
} private bool coolingDown = false;
private void shoot() public float coolDownTime = 2.0f;
{
float dir = Mathf.Sign(transform.localScale.x);
Vector2 pos = new Vector2(transform.position.x + dir * spawnDistance, transform.position.y);
switch (powerUpType) public GameObject healingBulletPrefab;
{ public GameObject trapDestroyingBulletPrefab;
case POWERUP_HEALINGBULLET:
GameObject bullet = Instantiate(healingBulletPrefab, pos, transform.rotation) as GameObject;
bullet.GetComponent<Bullet>().shoot(new Vector2(dir, 0));
break;
case POWERUP_TRAPDESTROYER:
GameObject trapbullet = Instantiate(trapDestroyingBulletPrefab, pos, transform.rotation) as GameObject;
trapbullet.GetComponent<Bullet>().shoot(new Vector2(dir, 0));
break;
default:
break;
}
}
private void coolDown() public float spawnDistance = 1.0f;
{ public void setPowerUpType(int type)
coolingDown = true; {
Invoke("coolDownOver", coolDownTime); powerUpType = type;
}
private void coolDownOver() }
{
coolingDown = false; private void shoot()
} {
float dir = Mathf.Sign(transform.localScale.x);
Vector2 pos = new Vector2(transform.position.x + dir * spawnDistance, transform.position.y);
private bool canShoot() switch (powerUpType)
{ {
return (!coolingDown) && powerUpType != POWERUP_NONE; case POWERUP_HEALINGBULLET:
GameObject bullet = Instantiate(healingBulletPrefab, pos, transform.rotation) as GameObject;
bullet.GetComponent<Bullet>().shoot(new Vector2(dir, 0));
break;
case POWERUP_TRAPDESTROYER:
GameObject trapbullet = Instantiate(trapDestroyingBulletPrefab, pos, transform.rotation) as GameObject;
trapbullet.GetComponent<Bullet>().shoot(new Vector2(dir, 0));
break;
default:
break;
} }
}
private void coolDown()
{
coolingDown = true;
Invoke("coolDownOver", coolDownTime);
}
private void coolDownOver()
{
coolingDown = false;
}
private bool canShoot()
{
return (!coolingDown) && powerUpType != POWERUP_NONE;
}
} }
...@@ -2,77 +2,80 @@ ...@@ -2,77 +2,80 @@
using System.Collections; using System.Collections;
using UnityEngine.UI; using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour { public class PlayerHealth : MonoBehaviour
{
public float maxHealth = 100; public float maxHealth = 100;
public float currentHealth = 100; public float currentHealth = 100;
private bool alive = true; private bool alive = true;
private Scrollbar healthbar; private Scrollbar healthbar;
private PlayerControl playerControl; private PlayerControl playerControl;
private bool hasShield = false; private bool hasShield = false;
public void init(int playerNumber) public void init(int playerNumber)
{ {
string healthbarName = "HealthBar" + playerNumber; string healthbarName = "HealthBar" + playerNumber;
string healthbarParentName = "HealthBarParent" + playerNumber; //wichtig um healthbars von nicht vorhandenen spielern auszublenden string healthbarParentName = "HealthBarParent" + playerNumber; //wichtig um healthbars von nicht vorhandenen spielern auszublenden
GameObject healthbarParent = GameObject.Find(healthbarParentName); GameObject healthbarParent = GameObject.Find(healthbarParentName);
//activate all children, which are disabled by default:
foreach (Transform child in healthbarParent.transform)
{
child.gameObject.SetActive(true);
}
healthbar = GameObject.Find(healthbarName).GetComponent<Scrollbar>();
if (name.EndsWith("(Clone)")) //activate all children, which are disabled by default:
{ foreach (Transform child in healthbarParent.transform)
name = name.Split(new char[] { '(' })[0]; {
} child.gameObject.SetActive(true);
} }
// Update is called once per frame healthbar = GameObject.Find(healthbarName).GetComponent<Scrollbar>();
void Update () {
if (alive && currentHealth <= 0)
{
Debug.Log("Player " + name + " dead.");
alive = false;
((GameStateTracker) Object.FindObjectOfType(typeof(GameStateTracker))).playerDied(name);
healthbar.gameObject.SetActive(false); //hide healthbar
Destroy(gameObject);
}
}
public float getCurrentHealth() if (name.EndsWith("(Clone)"))
{ {
return currentHealth; name = name.Split(new char[] { '(' })[0];
} }
}
//updated die ui healthbar. // Update is called once per frame
private void updateHealthbar() void Update()
{
if (alive && currentHealth <= 0)
{ {
if (healthbar) Debug.Log("Player " + name + " dead.");
{ alive = false;
healthbar.size = currentHealth / maxHealth; ((GameStateTracker)Object.FindObjectOfType(typeof(GameStateTracker))).playerDied(name);
} healthbar.gameObject.SetActive(false); //hide healthbar
Destroy(gameObject);
} }
}
/// <summary> public float getCurrentHealth()
/// Erhöht bzw. erniedrigt aktuelle Gesundheit um Wert h, Gesundheit kann nicht höher werden als maxHealth. {
/// </summary> return currentHealth;
/// <param name="h"></param> }
public void changeHealthBy(float h)
{
if (hasShield && h < 0) return;
currentHealth += h; //updated die ui healthbar.
if (currentHealth > maxHealth) currentHealth = maxHealth; private void updateHealthbar()
updateHealthbar(); {
if (healthbar)
{
healthbar.size = currentHealth / maxHealth;
} }
}
public void setShield(bool s) { /// <summary>
Debug.Log("Shield " + s + " accepted"); /// Erhöht bzw. erniedrigt aktuelle Gesundheit um Wert h, Gesundheit kann nicht höher werden als maxHealth.
hasShield = s; /// </summary>
} /// <param name="h"></param>
public void changeHealthBy(float h)
{
if (hasShield && h < 0) return;
currentHealth += h;
if (currentHealth > maxHealth) currentHealth = maxHealth;
updateHealthbar();
}
public void setShield(bool s)
{
Debug.Log("Shield " + s + " accepted");
hasShield = s;
}
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
using GamepadInput; using GamepadInput;
public enum controlType : int { WASD = 0, ARROWS = 1, GAMEPAD1 = 2, GAMEPAD2 = 3, GAMEPAD3=4, GAMEPAD4=5} public enum controlType : int { WASD = 0, ARROWS = 1, GAMEPAD1 = 2, GAMEPAD2 = 3, GAMEPAD3 = 4, GAMEPAD4 = 5 }
public class PlayerInputMapping : MonoBehaviour { public class PlayerInputMapping : MonoBehaviour
{
private enum Keys : int { Left = 0, Right, Up, Down, Jump, Dash, Shoot }; private enum Keys : int { Left = 0, Right, Up, Down, Jump, Dash, Shoot };
KeyCode[] keyCodes = new KeyCode[Keys.GetNames(typeof(Keys)).Length]; KeyCode[] keyCodes = new KeyCode[Keys.GetNames(typeof(Keys)).Length];
bool usesGamepad; bool usesGamepad;
GamePad.Index gamepadIndex; GamePad.Index gamepadIndex;
public void set(controlType controls) public void set(controlType controls)
{
usesGamepad = true;
#region switch case controls
switch (controls)
{ {
usesGamepad = true; case controlType.WASD:
#region switch case controls usesGamepad = false;
switch (controls) keyCodes[(int)Keys.Right] = KeyCode.D;
{ keyCodes[(int)Keys.Left] = KeyCode.A;
case controlType.WASD: keyCodes[(int)Keys.Up] = KeyCode.W;
usesGamepad = false; keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Right] = KeyCode.D; keyCodes[(int)Keys.Down] = KeyCode.S;
keyCodes[(int)Keys.Left] = KeyCode.A; keyCodes[(int)Keys.Dash] = KeyCode.Space;
keyCodes[(int)Keys.Up] = KeyCode.W; keyCodes[(int)Keys.Shoot] = KeyCode.LeftShift;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up]; break;
keyCodes[(int)Keys.Down] = KeyCode.S;
keyCodes[(int)Keys.Dash] = KeyCode.Space;
keyCodes[(int)Keys.Shoot] = KeyCode.LeftShift;
break;
case controlType.ARROWS: case controlType.ARROWS:
usesGamepad = false; usesGamepad = false;
keyCodes[(int)Keys.Right] = KeyCode.RightArrow; keyCodes[(int)Keys.Right] = KeyCode.RightArrow;
keyCodes[(int)Keys.Left] = KeyCode.LeftArrow; keyCodes[(int)Keys.Left] = KeyCode.LeftArrow;
keyCodes[(int)Keys.Up] = KeyCode.UpArrow; keyCodes[(int)Keys.Up] = KeyCode.UpArrow;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up]; keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Down] = KeyCode.DownArrow; keyCodes[(int)Keys.Down] = KeyCode.DownArrow;
keyCodes[(int)Keys.Dash] = KeyCode.RightControl; keyCodes[(int)Keys.Dash] = KeyCode.RightControl;
keyCodes[(int)Keys.Shoot] = KeyCode.RightShift; keyCodes[(int)Keys.Shoot] = KeyCode.RightShift;
break; break;
case controlType.GAMEPAD1: case controlType.GAMEPAD1:
gamepadIndex = GamePad.Index.One; gamepadIndex = GamePad.Index.One;
break; break;
case controlType.GAMEPAD2: case controlType.GAMEPAD2:
gamepadIndex = GamePad.Index.Two; gamepadIndex = GamePad.Index.Two;
break; break;
case controlType.GAMEPAD3: case controlType.GAMEPAD3:
gamepadIndex = GamePad.Index.Three; gamepadIndex = GamePad.Index.Three;
break; break;
case controlType.GAMEPAD4: case controlType.GAMEPAD4:
gamepadIndex = GamePad.Index.Four; gamepadIndex = GamePad.Index.Four;
break; break;
default: default:
break; break;
#endregion #endregion
}
} }
}
public bool isRightPressed() public bool isRightPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
{ Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex); return leftStick.x > 0.0f || dPad.x > 0.0f;
Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
return leftStick.x > 0.0f || dPad.x > 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Right]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Right]);
}
public bool isLeftPressed() public bool isLeftPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
{ Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex); return leftStick.x < 0.0f || dPad.x < 0.0f;
Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
return leftStick.x < 0.0f || dPad.x < 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Left]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Left]);
}
public bool isJumpPressed() public bool isJumpPressed()
{ {
if (usesGamepad) return GamePad.GetButton(GamePad.Button.A, gamepadIndex); if (usesGamepad) return GamePad.GetButton(GamePad.Button.A, gamepadIndex);
else return Input.GetKey(keyCodes[(int)Keys.Jump]); else return Input.GetKey(keyCodes[(int)Keys.Jump]);
} }
public bool isUpPressed() public bool isUpPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
{ Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex); return leftStick.y > 0.0f || dPad.y > 0.0f;
Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
return leftStick.y > 0.0f || dPad.y > 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Up]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Up]);
}
public bool isDownPressed() public bool isDownPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
{ Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex); return leftStick.y < 0.0f || dPad.y < 0.0f;
Vector2 dPad = GamePad.GetAxis(GamePad.Axis.Dpad, gamepadIndex);
return leftStick.y < 0.0f || dPad.y < 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Down]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Down]);
}
public bool isDashPressed() public bool isDashPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) return (GamePad.GetTrigger(GamePad.Trigger.LeftTrigger, gamepadIndex) > 0.01f) || (GamePad.GetTrigger(GamePad.Trigger.RightTrigger, gamepadIndex) > 0.01f)
{ || GamePad.GetButton(GamePad.Button.LeftShoulder, gamepadIndex) || GamePad.GetButton(GamePad.Button.RightShoulder, gamepadIndex);
return (GamePad.GetTrigger(GamePad.Trigger.LeftTrigger, gamepadIndex) > 0.01f) || (GamePad.GetTrigger(GamePad.Trigger.RightTrigger, gamepadIndex) > 0.01f)
|| GamePad.GetButton(GamePad.Button.LeftShoulder, gamepadIndex) || GamePad.GetButton(GamePad.Button.RightShoulder, gamepadIndex);
}
else return Input.GetKey(keyCodes[(int)Keys.Dash]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Dash]);
}
public bool isShootPressed() public bool isShootPressed()
{
if (usesGamepad)
{ {
if (usesGamepad) return GamePad.GetButton(GamePad.Button.X, gamepadIndex) || GamePad.GetButton(GamePad.Button.Y, gamepadIndex);
{
return GamePad.GetButton(GamePad.Button.X, gamepadIndex) || GamePad.GetButton(GamePad.Button.Y, gamepadIndex);
}
else return Input.GetKey(keyCodes[(int)Keys.Shoot]);
} }
else return Input.GetKey(keyCodes[(int)Keys.Shoot]);
}
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class PowerUpScript : MonoBehaviour { public class PowerUpScript : MonoBehaviour
{
/// <summary> /// <summary>
/// sollte übereinstimmen mit PlayerControl.POWERUP_XXX /// sollte übereinstimmen mit PlayerControl.POWERUP_XXX
/// 0 == none /// 0 == none
/// 1 == Heal /// 1 == Heal
/// 2 == destroyTrap /// 2 == destroyTrap
/// </summary> /// </summary>
public int type; public int type;
void OnTriggerEnter2D(Collider2D other) void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{ {
if (other.tag == "Player") other.GetComponent<PlayerControl>().setPowerUpType(type);
{ transform.position = new Vector2(50, 50);//TODO setze auf 1000 oder so, zur sicherheit.
other.GetComponent<PlayerControl>().setPowerUpType(type);
transform.position = new Vector2(50, 50);//TODO setze auf 1000 oder so, zur sicherheit.
}
} }
}
} }
...@@ -4,63 +4,65 @@ using System.Collections; ...@@ -4,63 +4,65 @@ using System.Collections;
public class Rocket : MonoBehaviour public class Rocket : MonoBehaviour
{ {
#region members #region members
public int damagePoints = 15; public int damagePoints = 15;
public float flyToTargetSpeed = 10f; public float flyToTargetSpeed = 10f;
public float speed = 1f; public float speed = 1f;
public float pushForce = 20f; //wie stark das target weggeschubst wird beim aufprall. public float pushForce = 20f; //wie stark das target weggeschubst wird beim aufprall.
private Rigidbody2D body; private Rigidbody2D body;
public Transform target; public Transform target;
public Animator explosionAnimator; public Animator explosionAnimator;
private GameObject explosion; private GameObject explosion;
#endregion #endregion
// Use this for initialization // Use this for initialization
void Start () { void Start()
body = GetComponent<Rigidbody2D>(); {
} body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (!target) return;
//update direction: // Update is called once per frame
Vector3 direction = target.position - transform.position; void Update()
body.velocity = Vector2.Lerp(body.velocity, (float)speed * direction.normalized, Time.deltaTime * flyToTargetSpeed); {
Quaternion newRotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y)); if (!target) return;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * flyToTargetSpeed);
}
void OnTriggerEnter2D(Collider2D other) //update direction:
Vector3 direction = target.position - transform.position;
body.velocity = Vector2.Lerp(body.velocity, (float)speed * direction.normalized, Time.deltaTime * flyToTargetSpeed);
Quaternion newRotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y));
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * flyToTargetSpeed);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{ {
if (other.tag == "Player") other.GetComponent<PlayerHealth>().changeHealthBy(-damagePoints);
{ Rigidbody2D otherBody = other.GetComponent<Rigidbody2D>();
other.GetComponent<PlayerHealth>().changeHealthBy(-damagePoints); Debug.Log(body.velocity.normalized * pushForce);
Rigidbody2D otherBody = other.GetComponent<Rigidbody2D>(); otherBody.velocity = Vector2.zero;
Debug.Log(body.velocity.normalized * pushForce); otherBody.AddForce(body.velocity.normalized * pushForce);
otherBody.velocity = Vector2.zero;
otherBody.AddForce(body.velocity.normalized * pushForce);
//explosion effect: //explosion effect:
explosion = GameObject.Instantiate(explosionAnimator.gameObject,transform.position,transform.rotation) as GameObject; explosion = GameObject.Instantiate(explosionAnimator.gameObject, transform.position, transform.rotation) as GameObject;
gameObject.GetComponent<SpriteRenderer>().enabled = false; gameObject.GetComponent<SpriteRenderer>().enabled = false;
gameObject.GetComponent<Collider2D>().enabled = false; gameObject.GetComponent<Collider2D>().enabled = false;
Invoke("destroy", 1.0f); Invoke("destroy", 1.0f);
}
} }
}
void destroy() void destroy()
{ {
Destroy(explosion); Destroy(explosion);
Destroy(gameObject); Destroy(gameObject);
} }
public void setTarget(Transform newTarget) public void setTarget(Transform newTarget)
{ {
target = newTarget; target = newTarget;
} }
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class ShieldScript : MonoBehaviour { public class ShieldScript : MonoBehaviour
{
PlayerHealth parentHealth; PlayerHealth parentHealth;
public float shieldingTime = 10; public float shieldingTime = 10;
// Use this for initialization // Use this for initialization
void Start() void Start()
{ {
Invoke("stopShielding", shieldingTime); Invoke("stopShielding", shieldingTime);
} }
void OnTriggerEnter2D(Collider2D other) void OnTriggerEnter2D(Collider2D other)
{
PlayerHealth oldHealth = parentHealth;
if (other.tag == "Player")
{ {
PlayerHealth oldHealth = parentHealth; parentHealth = other.GetComponent<PlayerHealth>();
if (other.tag == "Player") transform.position = other.transform.position; //hier schon position setzen
{ transform.parent = other.transform;
parentHealth = other.GetComponent<PlayerHealth>(); Debug.Log("Set shield from shield");
transform.position = other.transform.position; //hier schon position setzen parentHealth.setShield(true);
transform.parent = other.transform;
Debug.Log("Set shield from shield");
parentHealth.setShield(true);
}
if (oldHealth != null && oldHealth != parentHealth) oldHealth.setShield(false);
} }
if (oldHealth != null && oldHealth != parentHealth) oldHealth.setShield(false);
void stopShielding() }
{
if (parentHealth != null) parentHealth.setShield(false); void stopShielding()
Destroy(gameObject); {
} if (parentHealth != null) parentHealth.setShield(false);
Destroy(gameObject);
}
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class Turret : MonoBehaviour { public class Turret : MonoBehaviour
{
public GameObject rocketPrefab; public GameObject rocketPrefab;
private Transform target; private Transform target;
private Rocket currentRocket; private Rocket currentRocket;
// Update is called once per frame
void Update () {
if (!target) return;
Vector3 direction = target.position - transform.position; // Update is called once per frame
transform.rotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y)); void Update()
} {
if (!target) return;
public void setTarget(Transform newTarget) Vector3 direction = target.position - transform.position;
{ transform.rotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y));
target = newTarget; }
}
public void shoot() public void setTarget(Transform newTarget)
{ {
if (currentRocket) return; // do not shoot another rocket when there is one already flying. target = newTarget;
}
currentRocket = (GameObject.Instantiate(rocketPrefab, transform.position, transform.rotation) as GameObject).GetComponent<Rocket>(); public void shoot()
currentRocket.setTarget(target); {
} if (currentRocket) return; // do not shoot another rocket when there is one already flying.
currentRocket = (GameObject.Instantiate(rocketPrefab, transform.position, transform.rotation) as GameObject).GetComponent<Rocket>();
currentRocket.setTarget(target);
}
} }
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
public class TurretButton : MonoBehaviour { public class TurretButton : MonoBehaviour
{
public Turret cannon; // die entsprechende turret-cannon. public Turret cannon; // die entsprechende turret-cannon.
void OnCollisionEnter2D(Collision2D coll) void OnCollisionEnter2D(Collision2D coll)
{
//soll nur von oben ausloesen:
if (coll.gameObject.tag == "Player" && coll.relativeVelocity.x < 0.001f && coll.relativeVelocity.y > 0.2f)
{ {
//soll nur von oben ausloesen: cannon.setTarget(coll.gameObject.transform);
if (coll.gameObject.tag == "Player" && coll.relativeVelocity.x<0.001f && coll.relativeVelocity.y>0.2f) cannon.shoot();
{
cannon.setTarget(coll.gameObject.transform);
cannon.shoot();
}
} }
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment