Skip to content

Commit

Permalink
Shooting logic implemented, map can show nearby enemies
Browse files Browse the repository at this point in the history
  • Loading branch information
aworld1 committed Aug 4, 2021
1 parent 596c9a0 commit a813381
Show file tree
Hide file tree
Showing 8 changed files with 282 additions and 43 deletions.
16 changes: 10 additions & 6 deletions Assets/Scripts/GPS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ IEnumerator LocationCoroutine() {
+ Input.location.lastData.timestamp);*/
latitude = Input.location.lastData.latitude;
longitude = Input.location.lastData.longitude;
GameHandler.Data.PushPlayerInfo();
}

private static double LatToMeters(double lat) {
Expand Down Expand Up @@ -107,16 +108,19 @@ public static double[] GetRelativeMapPosition(double[] pos, double[] center, dou
}

public static double AngleBetweenPoints(double lat1, double long1, double lat2, double long2) {
var dLon = (long2 - long1);
var dLon = long2 - long1;

var y = Math.Sin(dLon) * Math.Cos(lat2);
var x = Math.Cos(lat1) * Math.Sin(lat2) - Math.Sin(lat1)
* Math.Cos(lat2) * Math.Cos(dLon);
var b = Math.Atan2(y, x);
b = b * 180 / Math.PI;
b = (b + 360) % 360;
b = 360 - b;
return b;

var bearing = Math.Atan2(y, x);

bearing = Mathf.Rad2Deg * bearing;
bearing = (bearing + 360) % 360;
bearing = 360 - bearing;

return bearing;
}

public static double DistanceBetweenPoints(double lat1, double lon1, double lat2, double lon2) {
Expand Down
30 changes: 29 additions & 1 deletion Assets/Scripts/GameData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
public class GameData {
public string RoomCode;
public string PlayerName;
public string Team;
public double[] Center;
public int Size;
public int Kills;
Expand All @@ -16,10 +17,12 @@ public class GameData {
public List<Dictionary<string, object>> FloorWeapons;
public Dictionary<string, object> PrimaryWeapon;
public Dictionary<string, object> SecondaryWeapon;
public Dictionary<string, object> PlayerInfo;

public void SetupGame(string code, string nm, Dictionary<string, string> center) {
public void SetupGame(string code, string nm, string team, Dictionary<string, string> center) {
RoomCode = code;
PlayerName = nm;
Team = team;
Center = new[] {double.Parse(center["lat"]), double.Parse(center["long"])};
Health = 100;
Kills = 0;
Expand All @@ -45,6 +48,7 @@ await ServerHandler.GetRoomAttribute(RoomCode, "size").ContinueWith(result => {
Size = int.Parse(result.Result.Value.ToString());
});
await PrepWeapons();
await GetPlayerInfo();

}

Expand All @@ -61,4 +65,28 @@ await ServerHandler.GetRoomAttribute(RoomCode, "weapons").ContinueWith(async res
}
});
}

public async void PushPlayerInfo() {
if (GPS.CurrentTime() - ServerHandler.LastLocationUpdate < ServerHandler.LocationBuffer) return;
await ServerHandler.UpdateField("Rooms/" + RoomCode + "/players/" + PlayerName,
new Dictionary<string, object> {
["kills"] = Kills,
["deaths"] = Deaths,
["lat"] = GPS.Instance.latitude + "",
["long"] = GPS.Instance.longitude + ""
});
ServerHandler.LastLocationUpdate = GPS.CurrentTime();
}

public async Task GetPlayerInfo() {
if (GPS.CurrentTime() - ServerHandler.LastInformationPull < ServerHandler.LocationBuffer) return;
await ServerHandler.GetRoomAttribute(RoomCode, "players").ContinueWith(result => {
PlayerInfo = new Dictionary<string, object>();
var list = (Dictionary<string, object>)result.Result.Value;
foreach (var prop in list) {
if (!PlayerInfo.ContainsKey(prop.Key)) PlayerInfo.Add(prop.Key, prop.Value);
}
});
ServerHandler.LastInformationPull = GPS.CurrentTime();
}
}
7 changes: 6 additions & 1 deletion Assets/Scripts/GameHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ private void ShowUI() {
UIHandler.ShowHealth(healthBar, healthPoints);
}

public void FireResponse() {
public async void FireResponse() {
if ((bool) Data.PrimaryWeapon["reloading"]) {
Data.PrimaryWeapon["reloading"] = false;
UIHandler.StopAudio(audio);
Expand All @@ -53,6 +53,11 @@ public void FireResponse() {
if (FireWeapon()) {
UIHandler.PlayAudio(audio, "Fire/" + (string)Data.PrimaryWeapon["name"]);
Data.PrimaryWeapon["lastFired"] = GPS.CurrentTime();
await Data.GetPlayerInfo();
var hit = ServerHandler.FireWeapon(Data.PrimaryWeapon);
if (hit) {
UIHandler.PlayAudio(audio, "Noise/beep");
}
return;
}
UIHandler.PlayAudio(audio, "Noise/empty");
Expand Down
17 changes: 9 additions & 8 deletions Assets/Scripts/HostJoinHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
using Random = UnityEngine.Random;

public class HostJoinHandler : MonoBehaviour {
// Host Page
[Header("Host Page")]
public TMP_InputField roomSize;
public TMP_Dropdown gamemode;

// Join Page
[Header("Join Page")]
public TMP_InputField playerName;
public TMP_InputField roomCode;
public async void HostGame() {
Expand Down Expand Up @@ -40,7 +40,7 @@ await GetUniqueCode().ContinueWith(result => {
weapons[i + ""] = weaponsArr[i];
}
var dict = new Dictionary<string, object> {
["locations/" + nm] = loc,
["players/" + nm] = loc,
["center"] = loc,
["gamemode"] = mode,
["size"] = size,
Expand All @@ -50,7 +50,7 @@ await GetUniqueCode().ContinueWith(result => {
await ServerHandler.UpdateField("Rooms/" + code, dict);
switch(mode) {
case "Deathmatch":
GameHandler.Data.SetupGame(code, nm, loc);
GameHandler.Data.SetupGame(code, nm, nm, loc);
PrepDeathmatch();
break;
}
Expand All @@ -66,8 +66,9 @@ private void PrepDeathmatch() {

private async void JoinDeathmatch(Dictionary<string, object> dict) {
dict ??= new Dictionary<string, object>();
dict["scoreboard/" + GameHandler.Data.PlayerName + "/kills"] = 0;
dict["scoreboard/" + GameHandler.Data.PlayerName + "/deaths"] = 0;
dict["players/" + GameHandler.Data.PlayerName + "/kills"] = 0;
dict["players/" + GameHandler.Data.PlayerName + "/deaths"] = 0;
dict["players/" + GameHandler.Data.PlayerName + "/team"] = GameHandler.Data.PlayerName;
await ServerHandler.UpdateField("Rooms/" + GameHandler.Data.RoomCode, dict);
await GameHandler.Data.SetupDeathmatch();
SceneHandler.SwitchScene("Deathmatch Page");
Expand Down Expand Up @@ -102,15 +103,15 @@ await ServerHandler.DoesNameExistInRoom(code, nm).ContinueWith(result => {
var stringLoc = new Dictionary<string, string> {
["lat"] = GPS.Instance.latitude + "", ["long"] = GPS.Instance.longitude + ""
};
await ServerHandler.UpdateField("Rooms/" + code + "/locations/" + nm, loc);
await ServerHandler.UpdateField("Rooms/" + code + "/players/" + nm, loc);
SetInfo(code, nm);
var mode = "";
await ServerHandler.GetRoomAttribute(code, "gamemode").ContinueWith(result => {
mode = result.Result.Value.ToString();
});
switch(mode) {
case "Deathmatch":
GameHandler.Data.SetupGame(code, nm, stringLoc);
GameHandler.Data.SetupGame(code, nm, nm, stringLoc);
JoinDeathmatch(null);
break;
}
Expand Down
37 changes: 34 additions & 3 deletions Assets/Scripts/MapHandler.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;
Expand All @@ -25,10 +26,12 @@ public class MapHandler : MonoBehaviour {
public static bool PickupUpdate;
private bool pickingUp;
private bool firstAwake;
private bool resetting;

private void Start() {
prevLocs = new[] { GPS.Instance.latitude, GPS.Instance.longitude };
weaponSelected = 1;
resetting = false;
updatedNearby = false;
pickingUp = false;
PickupUpdate = false;
Expand All @@ -47,6 +50,7 @@ private void Update() {
HandleWeapons();
ShowOwnedWeapons();
ShowNearbyWeapons();
ShowEnemies();
}

private void ClearWeapons() {
Expand All @@ -65,6 +69,28 @@ public void SetSelectedWeapon(int num) {
weaponSelected = num;
}

private void ShowEnemies() {
foreach (var t in GameHandler.Data.PlayerInfo) {
if (t.Key == GameHandler.Data.PlayerName) continue;
var val = (Dictionary<string, object>) t.Value;
var lat = double.Parse(val["lat"].ToString(), System.Globalization.NumberStyles.Float);
var lon = double.Parse(val["long"].ToString(), System.Globalization.NumberStyles.Float);
var pos = GPS.GetRelativeMapPosition(new[] {GPS.Instance.latitude, GPS.Instance.longitude},
new[] {lat, lon}, (double)GameHandler.Data.Size / 2);
if (math.abs(pos[0]) > 1 || math.abs(pos[1]) > 1) {
continue;
}
var enemy = Instantiate(weaponSample, weaponsContainer.transform, true);
enemy.transform.localScale = new Vector3(0.7f, 0.7f, 1);
var rect = mapTransform.rect;
var scaledPos = new[] { pos[0] * rect.width / -2.2f, pos[1] * rect.height / 2.2f };
var comp = enemy.GetComponent<RectTransform>();
comp.anchoredPosition = new Vector2((float)scaledPos[0],(float)scaledPos[1]);
enemy.GetComponent<Image>().sprite = Resources.Load<Sprite>("Images/dot");
enemy.GetComponent<Image>().color = Color.red;
}
}

private void ShowOwnedWeapons() {
var primaryObj = primaryWeapon;
var secondObj = secondaryWeapon;
Expand Down Expand Up @@ -112,15 +138,19 @@ private void HandleWeapons() {
}

private void ResetWeaponObjs() {
if (resetting) return;
resetting = true;
weaponObjs = new List<WeaponObject>();
foreach (var t in GameHandler.Data.FloorWeapons) {
t["lat"] = Double.Parse(t["lat"].ToString(), System.Globalization.NumberStyles.Float);
t["long"] = Double.Parse(t["long"].ToString(), System.Globalization.NumberStyles.Float);
foreach (var t in GameHandler.Data.FloorWeapons
.Where(t => t != null && t.ContainsKey("lat"))) {
t["lat"] = double.Parse(t["lat"].ToString(), System.Globalization.NumberStyles.Float);
t["long"] = double.Parse(t["long"].ToString(), System.Globalization.NumberStyles.Float);
var pos = GPS.GetRelativeMapPosition(new[] {GPS.Instance.latitude, GPS.Instance.longitude},
new[] {(double)t["lat"], (double)t["long"]}, (double)GameHandler.Data.Size / 2);
weaponObjs.Add(new WeaponObject((string)t["name"], pos[0], pos[1],
(double)t["lat"], (double)t["long"]));
}
resetting = false;
}

private void SetWeaponObjTargets() {
Expand Down Expand Up @@ -184,6 +214,7 @@ private void ShowNearbyWeapons() {
updatedNearby = true;
}

// ReSharper disable once MemberCanBePrivate.Global
public async void NearbyResponse(int i) {
if (pickingUp) return;
pickingUp = true;
Expand Down
80 changes: 75 additions & 5 deletions Assets/Scripts/ServerHandler.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading.Tasks;
using Firebase.Database;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Random = System.Random;
#pragma warning disable 4014

public static class ServerHandler {
private static readonly DatabaseReference DataRef = FirebaseDatabase.DefaultInstance.RootReference;
public const int DeathmatchMaxKills = 5;
public const int DeathmatchTimeLimit = 300;
public const int PickupRange = 10;
public const double RevealWeaponRange = 0.7;
public const int LocationBuffer = 3000;
public static double LastLocationUpdate = 0;
public static double LastInformationPull = 0;

private static async Task<DataSnapshot> GetRoom(string room) {
return await FirebaseDatabase.DefaultInstance
Expand Down Expand Up @@ -67,6 +73,47 @@ public static async Task UpdateField(string path, Dictionary<string, object> con
await DataRef.Child(path).UpdateChildrenAsync(content);
}

public static bool FireWeapon(Dictionary<string, object> weapon) {
var hitPlayer = "";
if ((int) weapon["reserve"] != -1) {
for (var i = 0; i < (int) weapon["bullets"]; i++) {
var gyro = (Input.compass.trueHeading + new Random().Next(0, 1000) / 500d
* (int) weapon["inaccuracy"] -
(int) weapon["inaccuracy"] + 360) % 360;
var smallestDistance = (int) weapon["range"] + 1;
foreach (var t in GameHandler.Data.PlayerInfo) {
var pl = (Dictionary<string, object>) t.Value;
if (t.Key == GameHandler.Data.PlayerName || pl["team"].ToString() == GameHandler.Data.Team) continue;
var a = (GPS.AngleBetweenPoints(GPS.Instance.latitude, GPS.Instance.longitude,
Convert.ToDouble(pl["lat"]), Convert.ToDouble(pl["long"])) + 90) % 360;
var d = GPS.DistanceBetweenPoints(GPS.Instance.latitude, GPS.Instance.longitude,
Convert.ToDouble(pl["lat"]), Convert.ToDouble(pl["long"]));
var acceptableMiss = 90 - d / (int) weapon["range"] * 90;
Debug.Log("Angle: " + a + " \nCompass: " + gyro);
if (Math.Abs(a - gyro) < acceptableMiss ||
Math.Abs(a - gyro) > 360 - acceptableMiss && d < smallestDistance) {
Debug.Log("HIT!");
hitPlayer = t.Key;
}
}
}
}
else {
foreach (var t in GameHandler.Data.PlayerInfo) {
var pl = (Dictionary<string, object>) t.Value;
if (t.Key == GameHandler.Data.PlayerName || pl["team"].ToString() == GameHandler.Data.Team) continue;
var d = GPS.DistanceBetweenPoints(GPS.Instance.latitude, GPS.Instance.longitude,
Convert.ToDouble(pl["lat"]), Convert.ToDouble(pl["long"]));
if (d <= (int) weapon["range"]) {
hitPlayer = t.Key;
}
}
}
if (hitPlayer == "") return false;
CreateEvent("Hit$" + hitPlayer + "$" + GameHandler.Data.PlayerName + "$" + (int) weapon["damage"]);
return true;
}

public static async Task<bool> PickupWeapon(string room, Dictionary<string, object> pickup, Dictionary<string, object> drop) {
return await await GetRoomAttribute(room, "weapons").ContinueWith(async result => {
var snapshot = (List<object>)result.Result.Value;
Expand Down Expand Up @@ -94,23 +141,46 @@ public static async Task<bool> PickupWeapon(string room, Dictionary<string, obje
await UpdateField("Rooms/" + room, new Dictionary<string, object> {
["weapons"] = weapons
});
await UpdateField("Rooms/" + room + "/Events", new Dictionary<string, object> {
[GPS.RealTime() + "" + new System.Random().Next(0, 99999)] = "WeaponUpdate"
});
CreateEvent("WeaponUpdate");
return true;
});
}

private static async Task CreateEvent(string message) {
var sig = GPS.RealTime() + "" + new Random().Next(0, 99999);
await UpdateField("Rooms/" + GameHandler.Data.RoomCode + "/Events",
new Dictionary<string, object> {
[sig] = message
});
await Task.Delay(3000);
await UpdateField("Rooms/" + GameHandler.Data.RoomCode + "/Events",
new Dictionary<string, object> {
[sig] = null
});
}

public static void SubscribeToEvents(string room) {
FirebaseDatabase.DefaultInstance
.GetReference("Rooms/" + room + "/Events")
.ChildAdded += EventDetected;
}

private static async void EventDetected(object sender, ChildChangedEventArgs args) {
if ((string)args.Snapshot.Value == "WeaponUpdate") {
var ev = (string) args.Snapshot.Value;
if (ev == "WeaponUpdate") {
await GameHandler.Data.PrepWeapons();
MapHandler.PickupUpdate = true;
}
else if (ev.Substring(0, 3) == "Hit" && GameHandler.Data.Health > 0) {
var info = ev.Split('$');
if (info[1] != GameHandler.Data.PlayerName) return;
GameHandler.Data.Health -= Convert.ToInt32(info[3]);
if (GameHandler.Data.Health > 0) return;
CreateEvent("Kill");
GameHandler.Data.Health = 0;
}
else if (ev == "Kill") {
GameHandler.Data.Kills++;
}
}
}
Loading

0 comments on commit a813381

Please sign in to comment.