Commit 8d61ac10 by Alisa Jung

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

parent d87c20d0
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;
......
...@@ -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