Commit 8d61ac10 by Alisa Jung

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

parent d87c20d0
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
public class Bullet : MonoBehaviour
{
public int healingPoints = 10;
public bool destroyTrap = false;
public int speed = 5;
public int healingPoints = 10;
public bool destroyTrap = false;
public int speed = 5;
/// <summary>
/// Das aufrufen, wenn die Kugel wirklich losgeschossen werden soll.
/// </summary>
/// <param name="direction"></param>
public void shoot(Vector2 direction)
/// <summary>
/// Das aufrufen, wenn die Kugel wirklich losgeschossen werden soll.
/// </summary>
/// <param name="direction"></param>
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);
}
void OnTriggerEnter2D(Collider2D other)
else if (destroyTrap && other.tag == "Trap")
{
//Debug.Log("Bullet colide with " + other.name);
if (healingPoints > 0 && other.tag == "Player")
{
other.GetComponent<PlayerHealth>().changeHealthBy(healingPoints);
Destroy(gameObject);
}
else if (destroyTrap && other.tag == "Trap")
{
other.GetComponent<Trap>().destroyTrap();
Destroy(gameObject);
}
other.GetComponent<Trap>().destroyTrap();
Destroy(gameObject);
}
}
}
using UnityEngine;
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()
{
startScale = transform.localScale;
}
// Update is called once per frame
void Update () {
if (parentHealth)
{
parentHealth.changeHealthBy(-constantDamagepoints * Time.deltaTime);
}
}
void Start()
{
startScale = transform.localScale;
}
void OnTriggerEnter2D(Collider2D other)
// Update is called once per frame
void Update()
{
if (parentHealth)
{
if (other.tag == "Player")
{
parentHealth = other.GetComponent<PlayerHealth>();
transform.position = other.transform.position; //hier schon position setzen
transform.parent = other.transform;
transform.localScale = startScale;
Invoke("stopBurning", burningTime);
}
parentHealth.changeHealthBy(-constantDamagepoints * Time.deltaTime);
}
}
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;
using System.Collections.Generic;
using UnityEngine.UI;
public class GameMaster : MonoBehaviour {
public class GameMaster : MonoBehaviour
{
DeserializedLevelsLoader levelLoader;
public PlayerControl[] playerPrefabs;
public GameObject gameOverPanel;
public Text rankingText;
DeserializedLevelsLoader levelLoader;
public PlayerControl[] playerPrefabs;
public GameObject gameOverPanel;
public Text rankingText;
// Use this for initialization
void Start () {
levelLoader = new DeserializedLevelsLoader();
levelLoader.load();
}
// Use this for initialization
void Start()
{
levelLoader = new DeserializedLevelsLoader();
levelLoader.load();
}
public void loadLevel(int numberOfPlayers, int level = -1)
{
if (level < 0)
level = Random.Range(0, levelLoader.getLevelCount());
levelLoader.loadLevel(level);
public void loadLevel(int numberOfPlayers, int level = -1)
{
if (level < 0)
level = Random.Range(0, levelLoader.getLevelCount());
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"))
Object.Destroy(player, 0f);
count = startPositions.Length;
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");
if (count > startPositions.Length)
{
count = startPositions.Length;
Debug.LogError("map is capped at " + count + " players");
}
private static void shuffle<T>(T[] array)
{
int i = array.Length;
while (i > 1)
{
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++)
{
PlayerControl player = (PlayerControl) Object.Instantiate(
playerPrefabs[i % playerPrefabs.Length],
startPositions[i].transform.position,
Quaternion.identity);
player.init(i + 1);
}
Debug.Log(ranking.Count);
if (ranking.Count > 0)
{
rankingText.text = "1st: " + ranking[0];
}
private static void shuffle<T>(T[] array)
if (ranking.Count > 1)
{
int i = array.Length;
while (i > 1)
{
int k = Random.Range(0, i--);
T t = array[k];
array[k] = array[i];
array[i] = t;
}
rankingText.text += "\n2nd: " + ranking[1];
}
public void gameOver(List<string> ranking)
if (ranking.Count > 2)
{
gameOverPanel.SetActive(true);
Debug.Log(ranking.Count);
if (ranking.Count > 0)
{
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];
}
rankingText.text += "\n3rd: " + ranking[2];
}
if (ranking.Count > 3)
{
rankingText.text += "\n4th: " + ranking[3];
}
}
}
......@@ -2,72 +2,74 @@
using System.Collections;
using System.Collections.Generic;
public class GameStateTracker : MonoBehaviour {
public class GameStateTracker : MonoBehaviour
{
private int numberOfPlayers;
/// <summary>
/// Numbers of Player ranked 4th to winner
/// </summary>
private int fourthPlayer;
private int thirdPlayer;
private int secondPlayer;
private int winnerPlayer;
private int numberOfPlayers;
/// <summary>
/// Numbers of Player ranked 4th to winner
/// </summary>
private int fourthPlayer;
private int thirdPlayer;
private int secondPlayer;
private int winnerPlayer;
private List<string> ranking;
private GameMaster gameMaster;
private List<string> ranking;
private GameMaster gameMaster;
void Awake()
{
ranking = new List<string>();
}
void Awake()
{
ranking = new List<string>();
}
// Use this for initialization
void Start () {
gameMaster = GetComponent<GameMaster>();
}
// Use this for initialization
void Start()
{
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);
}
public void setNumberOfPlayers(int players)
if (ranking.Count >= numberOfPlayers - 1)
{
numberOfPlayers = players;
gameOver();
}
}
public void playerDied(string name)
{
if (!ranking.Contains(name))
{
ranking.Add(name);
}
if (ranking.Count >= numberOfPlayers - 1)
{
gameOver();
}
}
public void gameOver()
{
Time.timeScale = 0.0f; //stops the game
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
//find the player who is still alive:
string playerStillAlive = "";
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
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
if (p.GetComponent<PlayerHealth>().getCurrentHealth() > 0)
{
playerStillAlive = p.name;
ranking.Add(playerStillAlive);
break;
}
}
gameMaster.gameOver(ranking); //shows the game over screen
}
}
......@@ -6,11 +6,12 @@ using System.IO;
using System.Xml;
using System.Linq;
public class DeserializedLevelsCrossChecker {
public class DeserializedLevelsCrossChecker
{
//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
public void crossCheck ()
public void crossCheck()
{
// create a list of /Resources/Prefabs for resources and Levels.Xml
List<string> resPrefabList = new List<string>();
......@@ -33,16 +34,16 @@ public class DeserializedLevelsCrossChecker {
fileInfos.Select(f => f.FullName).ToArray();
// Add each prefab's file name to prefabList and truncate the .prefab extension from the end
foreach (FileInfo fileInfo in fileInfos)
resPrefabList.Add (fileInfo.Name.Substring(0, fileInfo.Name.Length - ".prefab".Length));
foreach (FileInfo fileInfo in fileInfos)
resPrefabList.Add(fileInfo.Name.Substring(0, fileInfo.Name.Length - ".prefab".Length));
// Cross checks
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())
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
struct ItemChildStruct
{
public string name;
public float x;
public float y;
public float rot;
public float scalex;
public float scaley;
public string name;
public float x;
public float y;
public float rot;
public float scalex;
public float scaley;
}
// Cache prefabs in prefabDict
Dictionary<string,GameObject> prefabPool;
Dictionary<string, GameObject> prefabPool;
// Cache all items with locations
List<ItemStruct> sceneItemsList;
......@@ -43,12 +43,12 @@ public class DeserializedLevelsLoader
public const string xmlItemsGOName = "XmlItems";
public void load ()
public void load()
{
deserializedLevels = XmlIO.LoadXml<DeserializedLevels>("Levels");
}
public int getLevelCount ()
public int getLevelCount()
{
if (deserializedLevels == null)
throw new System.InvalidOperationException();
......@@ -56,7 +56,7 @@ public class DeserializedLevelsLoader
return deserializedLevels.levels.Length;
}
public void loadLevel (int levelIndex = 0)
public void loadLevel(int levelIndex = 0)
{
if (deserializedLevels == null)
throw new System.InvalidOperationException();
......@@ -68,8 +68,8 @@ public class DeserializedLevelsLoader
sceneItemsList = new List<ItemStruct>();
// if the XmlItems gameobject folder remained in the Hierarcy, then delete it
while (GameObject.Find (xmlItemsGOName) != null)
MonoBehaviour.DestroyImmediate(GameObject.Find (xmlItemsGOName));
while (GameObject.Find(xmlItemsGOName) != null)
MonoBehaviour.DestroyImmediate(GameObject.Find(xmlItemsGOName));
parentOfXmlItems = new GameObject(xmlItemsGOName).transform;
......@@ -116,12 +116,12 @@ public class DeserializedLevelsLoader
int k = 0;
foreach (DeserializedLevels.Item child in children)
{
item.children[k].name = child.prefab;
item.children[k].x = toFloatZeroIfNull(child.x);
item.children[k].y = toFloatZeroIfNull(child.y);
item.children[k].rot = toFloatZeroIfNull(child.rot);
item.children[k].scalex = toFloatOneIfNull(child.scalex);
item.children[k].scaley = toFloatOneIfNull(child.scaley);
item.children[k].name = child.prefab;
item.children[k].x = toFloatZeroIfNull(child.x);
item.children[k].y = toFloatZeroIfNull(child.y);
item.children[k].rot = toFloatZeroIfNull(child.rot);
item.children[k].scalex = toFloatOneIfNull(child.scalex);
item.children[k].scaley = toFloatOneIfNull(child.scaley);
}
sceneItemsList.Add(item);
......@@ -144,19 +144,19 @@ public class DeserializedLevelsLoader
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)
{
Debug.Log("Set child " + child.name);
setPos2D(t.gameObject, new Vector2(child.x, child.y));
setRot2D(t.gameObject, child.rot);
setScale2D(t.gameObject, child.scalex, child.scaley);
}
}
if (t.name == child.name)
{
Debug.Log("Set child " + child.name);
setPos2D(t.gameObject, new Vector2(child.x, child.y));
setRot2D(t.gameObject, child.rot);
setScale2D(t.gameObject, child.scalex, child.scaley);
}
}
}
}
// set parent
newGameObject.transform.parent = parentOfXmlItems;
......@@ -167,12 +167,12 @@ public class DeserializedLevelsLoader
// DONE, these are only helper functions below
// if no value then return zero or one, otherwise convert to float
float toFloatZeroIfNull (string value) { return value == null ? 0 : float.Parse(value); }
float toFloatOneIfNull (string value) { return value == null ? 1 : 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); }
void setPos2D(GameObject g, Vector2 pos)
{
g.transform.position = new Vector2 (
g.transform.position = new Vector2(
pos.x,
pos.y
);
......
......@@ -6,19 +6,19 @@ public class DeserializedLevelsSaver
{
public const string xmlItemsToExportGOName = "XmlItemsToExport";
public void saveExportItems ()
public void saveExportItems()
{
// Create XmlItemsToExport if does not exist yet
if (GameObject.Find (xmlItemsToExportGOName) == null)
if (GameObject.Find(xmlItemsToExportGOName) == null)
new GameObject(xmlItemsToExportGOName);
GameObject xmlItemsToExportGO = GameObject.Find (xmlItemsToExportGOName);
GameObject xmlItemsToExportGO = GameObject.Find(xmlItemsToExportGOName);
var xmlItemsToExportGOchildren = xmlItemsToExportGO.GetComponentsInChildren<Transform>();
// Check if any children exist
if (xmlItemsToExportGOchildren.Length == 0)
Debug.LogError ("Add the prefabs to " + xmlItemsToExportGOName);
Debug.LogError("Add the prefabs to " + xmlItemsToExportGOName);
DeserializedLevels.Level levelXml = new DeserializedLevels.Level();
......@@ -55,28 +55,28 @@ public class DeserializedLevelsSaver
int k = 0;
foreach (Transform t in item.GetComponentsInChildren<Transform>())
{
if (!t.parent.name.Equals("XmlItemsToExport"))
{
//GetComponentsInChildren gibt auch die Komponente aus dem Parent (also dem Objekt selbst) zurck
DeserializedLevels.Item child = new DeserializedLevels.Item();
Debug.Log("Add child " + t.name);
child.prefab = t.name;
child.x = toStringNullIfZero(t.position.x);
child.y = toStringNullIfZero(t.position.y);
child.rot = toStringNullIfZero(t.rotation.eulerAngles.z);
child.scalex = toStringNullIfOne(t.localScale.x);
child.scaley = toStringNullIfOne(t.localScale.y);
children[k] = child;
k++;
}
if (!t.parent.name.Equals("XmlItemsToExport"))
{
//GetComponentsInChildren gibt auch die Komponente aus dem Parent (also dem Objekt selbst) zurck
DeserializedLevels.Item child = new DeserializedLevels.Item();
Debug.Log("Add child " + t.name);
child.prefab = t.name;
child.x = toStringNullIfZero(t.position.x);
child.y = toStringNullIfZero(t.position.y);
child.rot = toStringNullIfZero(t.rotation.eulerAngles.z);
child.scalex = toStringNullIfOne(t.localScale.x);
child.scaley = toStringNullIfOne(t.localScale.y);
children[k] = child;
k++;
}
}
levelXml.items[i].children = (item.childCount > 0) ? children : null;
i++;
i++;
}
......@@ -87,12 +87,12 @@ public class DeserializedLevelsSaver
XmlIO.SaveXml<DeserializedLevels>(levelsXmlToExport, "./Assets/Resources/" + xmlItemsToExportGOName + ".xml");
}
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 toStringNullIfZero(float num) { return num == 0 ? 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
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));
s.Serialize(stream, deserializedXml);
......@@ -16,9 +16,9 @@ public static class XmlIO
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));
T deserializedXml = s.Deserialize(stream) as T;
......
......@@ -2,77 +2,80 @@
using System.Collections;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour {
public class PlayerHealth : MonoBehaviour
{
public float maxHealth = 100;
public float maxHealth = 100;
public float currentHealth = 100;
private bool alive = true;
private Scrollbar healthbar;
private PlayerControl playerControl;
private bool hasShield = false;
public float currentHealth = 100;
private bool alive = true;
private Scrollbar healthbar;
private PlayerControl playerControl;
private bool hasShield = false;
public void init(int playerNumber)
{
string healthbarName = "HealthBar" + playerNumber;
string healthbarParentName = "HealthBarParent" + playerNumber; //wichtig um healthbars von nicht vorhandenen spielern auszublenden
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>();
public void init(int playerNumber)
{
string healthbarName = "HealthBar" + playerNumber;
string healthbarParentName = "HealthBarParent" + playerNumber; //wichtig um healthbars von nicht vorhandenen spielern auszublenden
GameObject healthbarParent = GameObject.Find(healthbarParentName);
if (name.EndsWith("(Clone)"))
{
name = name.Split(new char[] { '(' })[0];
}
//activate all children, which are disabled by default:
foreach (Transform child in healthbarParent.transform)
{
child.gameObject.SetActive(true);
}
// Update is called once per frame
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);
}
}
healthbar = GameObject.Find(healthbarName).GetComponent<Scrollbar>();
public float getCurrentHealth()
if (name.EndsWith("(Clone)"))
{
return currentHealth;
name = name.Split(new char[] { '(' })[0];
}
}
//updated die ui healthbar.
private void updateHealthbar()
// Update is called once per frame
void Update()
{
if (alive && currentHealth <= 0)
{
if (healthbar)
{
healthbar.size = currentHealth / maxHealth;
}
Debug.Log("Player " + name + " dead.");
alive = false;
((GameStateTracker)Object.FindObjectOfType(typeof(GameStateTracker))).playerDied(name);
healthbar.gameObject.SetActive(false); //hide healthbar
Destroy(gameObject);
}
}
/// <summary>
/// Erhöht bzw. erniedrigt aktuelle Gesundheit um Wert h, Gesundheit kann nicht höher werden als maxHealth.
/// </summary>
/// <param name="h"></param>
public void changeHealthBy(float h)
{
if (hasShield && h < 0) return;
public float getCurrentHealth()
{
return currentHealth;
}
currentHealth += h;
if (currentHealth > maxHealth) currentHealth = maxHealth;
updateHealthbar();
//updated die ui healthbar.
private void updateHealthbar()
{
if (healthbar)
{
healthbar.size = currentHealth / maxHealth;
}
}
public void setShield(bool s) {
Debug.Log("Shield " + s + " accepted");
hasShield = s;
}
/// <summary>
/// Erhöht bzw. erniedrigt aktuelle Gesundheit um Wert h, Gesundheit kann nicht höher werden als maxHealth.
/// </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 System.Collections;
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];
bool usesGamepad;
GamePad.Index gamepadIndex;
KeyCode[] keyCodes = new KeyCode[Keys.GetNames(typeof(Keys)).Length];
bool usesGamepad;
GamePad.Index gamepadIndex;
public void set(controlType controls)
public void set(controlType controls)
{
usesGamepad = true;
#region switch case controls
switch (controls)
{
usesGamepad = true;
#region switch case controls
switch (controls)
{
case controlType.WASD:
usesGamepad = false;
keyCodes[(int)Keys.Right] = KeyCode.D;
keyCodes[(int)Keys.Left] = KeyCode.A;
keyCodes[(int)Keys.Up] = KeyCode.W;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Down] = KeyCode.S;
keyCodes[(int)Keys.Dash] = KeyCode.Space;
keyCodes[(int)Keys.Shoot] = KeyCode.LeftShift;
break;
case controlType.WASD:
usesGamepad = false;
keyCodes[(int)Keys.Right] = KeyCode.D;
keyCodes[(int)Keys.Left] = KeyCode.A;
keyCodes[(int)Keys.Up] = KeyCode.W;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Down] = KeyCode.S;
keyCodes[(int)Keys.Dash] = KeyCode.Space;
keyCodes[(int)Keys.Shoot] = KeyCode.LeftShift;
break;
case controlType.ARROWS:
usesGamepad = false;
keyCodes[(int)Keys.Right] = KeyCode.RightArrow;
keyCodes[(int)Keys.Left] = KeyCode.LeftArrow;
keyCodes[(int)Keys.Up] = KeyCode.UpArrow;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Down] = KeyCode.DownArrow;
keyCodes[(int)Keys.Dash] = KeyCode.RightControl;
keyCodes[(int)Keys.Shoot] = KeyCode.RightShift;
break;
case controlType.GAMEPAD1:
gamepadIndex = GamePad.Index.One;
break;
case controlType.GAMEPAD2:
gamepadIndex = GamePad.Index.Two;
break;
case controlType.GAMEPAD3:
gamepadIndex = GamePad.Index.Three;
break;
case controlType.GAMEPAD4:
gamepadIndex = GamePad.Index.Four;
break;
default:
break;
#endregion
}
case controlType.ARROWS:
usesGamepad = false;
keyCodes[(int)Keys.Right] = KeyCode.RightArrow;
keyCodes[(int)Keys.Left] = KeyCode.LeftArrow;
keyCodes[(int)Keys.Up] = KeyCode.UpArrow;
keyCodes[(int)Keys.Jump] = keyCodes[(int)Keys.Up];
keyCodes[(int)Keys.Down] = KeyCode.DownArrow;
keyCodes[(int)Keys.Dash] = KeyCode.RightControl;
keyCodes[(int)Keys.Shoot] = KeyCode.RightShift;
break;
case controlType.GAMEPAD1:
gamepadIndex = GamePad.Index.One;
break;
case controlType.GAMEPAD2:
gamepadIndex = GamePad.Index.Two;
break;
case controlType.GAMEPAD3:
gamepadIndex = GamePad.Index.Three;
break;
case controlType.GAMEPAD4:
gamepadIndex = GamePad.Index.Four;
break;
default:
break;
#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);
return leftStick.x > 0.0f || dPad.x > 0.0f;
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
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);
return leftStick.x < 0.0f || dPad.x < 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Left]);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
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]);
}
public bool isJumpPressed()
{
if (usesGamepad) return GamePad.GetButton(GamePad.Button.A, gamepadIndex);
else return Input.GetKey(keyCodes[(int)Keys.Jump]);
}
public bool isJumpPressed()
{
if (usesGamepad) return GamePad.GetButton(GamePad.Button.A, gamepadIndex);
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);
return leftStick.y > 0.0f || dPad.y > 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Up]);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
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]);
}
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);
return leftStick.y < 0.0f || dPad.y < 0.0f;
}
else return Input.GetKey(keyCodes[(int)Keys.Down]);
Vector2 leftStick = GamePad.GetAxis(GamePad.Axis.LeftStick, gamepadIndex);
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]);
}
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);
}
else return Input.GetKey(keyCodes[(int)Keys.Dash]);
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]);
}
public bool isShootPressed()
public bool isShootPressed()
{
if (usesGamepad)
{
if (usesGamepad)
{
return GamePad.GetButton(GamePad.Button.X, gamepadIndex) || GamePad.GetButton(GamePad.Button.Y, gamepadIndex);
}
else return Input.GetKey(keyCodes[(int)Keys.Shoot]);
return GamePad.GetButton(GamePad.Button.X, gamepadIndex) || GamePad.GetButton(GamePad.Button.Y, gamepadIndex);
}
else return Input.GetKey(keyCodes[(int)Keys.Shoot]);
}
}
using UnityEngine;
using System.Collections;
public class PowerUpScript : MonoBehaviour {
public class PowerUpScript : MonoBehaviour
{
/// <summary>
/// sollte übereinstimmen mit PlayerControl.POWERUP_XXX
/// 0 == none
/// 1 == Heal
/// 2 == destroyTrap
/// </summary>
public int type;
/// <summary>
/// sollte übereinstimmen mit PlayerControl.POWERUP_XXX
/// 0 == none
/// 1 == Heal
/// 2 == destroyTrap
/// </summary>
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;
public class Rocket : MonoBehaviour
{
#region members
public int damagePoints = 15;
public float flyToTargetSpeed = 10f;
public float speed = 1f;
public float pushForce = 20f; //wie stark das target weggeschubst wird beim aufprall.
#region members
public int damagePoints = 15;
public float flyToTargetSpeed = 10f;
public float speed = 1f;
public float pushForce = 20f; //wie stark das target weggeschubst wird beim aufprall.
private Rigidbody2D body;
public Transform target;
public Animator explosionAnimator;
private GameObject explosion;
#endregion
private Rigidbody2D body;
public Transform target;
public Animator explosionAnimator;
private GameObject explosion;
#endregion
// Use this for initialization
void Start () {
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (!target) return;
// Use this for initialization
void Start()
{
body = GetComponent<Rigidbody2D>();
}
//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);
}
// Update is called once per frame
void Update()
{
if (!target) return;
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>();
Debug.Log(body.velocity.normalized * pushForce);
otherBody.velocity = Vector2.zero;
otherBody.AddForce(body.velocity.normalized * pushForce);
other.GetComponent<PlayerHealth>().changeHealthBy(-damagePoints);
Rigidbody2D otherBody = other.GetComponent<Rigidbody2D>();
Debug.Log(body.velocity.normalized * pushForce);
otherBody.velocity = Vector2.zero;
otherBody.AddForce(body.velocity.normalized * pushForce);
//explosion effect:
explosion = GameObject.Instantiate(explosionAnimator.gameObject,transform.position,transform.rotation) as GameObject;
//explosion effect:
explosion = GameObject.Instantiate(explosionAnimator.gameObject, transform.position, transform.rotation) as GameObject;
gameObject.GetComponent<SpriteRenderer>().enabled = false;
gameObject.GetComponent<Collider2D>().enabled = false;
gameObject.GetComponent<SpriteRenderer>().enabled = false;
gameObject.GetComponent<Collider2D>().enabled = false;
Invoke("destroy", 1.0f);
}
Invoke("destroy", 1.0f);
}
}
void destroy()
{
Destroy(explosion);
Destroy(gameObject);
}
void destroy()
{
Destroy(explosion);
Destroy(gameObject);
}
public void setTarget(Transform newTarget)
{
target = newTarget;
}
public void setTarget(Transform newTarget)
{
target = newTarget;
}
}
using UnityEngine;
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
void Start()
{
Invoke("stopShielding", shieldingTime);
}
// Use this for initialization
void Start()
{
Invoke("stopShielding", shieldingTime);
}
void OnTriggerEnter2D(Collider2D other)
void OnTriggerEnter2D(Collider2D other)
{
PlayerHealth oldHealth = parentHealth;
if (other.tag == "Player")
{
PlayerHealth oldHealth = parentHealth;
if (other.tag == "Player")
{
parentHealth = other.GetComponent<PlayerHealth>();
transform.position = other.transform.position; //hier schon position setzen
transform.parent = other.transform;
Debug.Log("Set shield from shield");
parentHealth.setShield(true);
}
if (oldHealth != null && oldHealth != parentHealth) oldHealth.setShield(false);
parentHealth = other.GetComponent<PlayerHealth>();
transform.position = other.transform.position; //hier schon position setzen
transform.parent = other.transform;
Debug.Log("Set shield from shield");
parentHealth.setShield(true);
}
if (oldHealth != null && oldHealth != parentHealth) oldHealth.setShield(false);
void stopShielding()
{
if (parentHealth != null) parentHealth.setShield(false);
Destroy(gameObject);
}
}
void stopShielding()
{
if (parentHealth != null) parentHealth.setShield(false);
Destroy(gameObject);
}
}
using UnityEngine;
using System.Collections;
public class Turret : MonoBehaviour {
public class Turret : MonoBehaviour
{
public GameObject rocketPrefab;
private Transform target;
private Rocket currentRocket;
public GameObject rocketPrefab;
private Transform target;
private Rocket currentRocket;
// Update is called once per frame
void Update () {
if (!target) return;
Vector3 direction = target.position - transform.position;
transform.rotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y));
}
// Update is called once per frame
void Update()
{
if (!target) return;
public void setTarget(Transform newTarget)
{
target = newTarget;
}
Vector3 direction = target.position - transform.position;
transform.rotation = Quaternion.Euler(0, 0, -Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.y));
}
public void shoot()
{
if (currentRocket) return; // do not shoot another rocket when there is one already flying.
public void setTarget(Transform newTarget)
{
target = newTarget;
}
currentRocket = (GameObject.Instantiate(rocketPrefab, transform.position, transform.rotation) as GameObject).GetComponent<Rocket>();
currentRocket.setTarget(target);
}
public void shoot()
{
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 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:
if (coll.gameObject.tag == "Player" && coll.relativeVelocity.x<0.001f && coll.relativeVelocity.y>0.2f)
{
cannon.setTarget(coll.gameObject.transform);
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