Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -290,4 +290,8 @@ $RECYCLE.BIN/
# Windows shortcuts
*.lnk


# Environment file
.env

# End of https://www.toptal.com/developers/gitignore/api/macos,windows,linux,unity,intellij+all,clion+all
5 changes: 4 additions & 1 deletion Assets/Scripts/PlayerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Text;
using UnityEngine;
using SocketIOClient;
using CandyCoded.env;

public class PlayerMovement : MonoBehaviour
{
Expand All @@ -23,11 +24,13 @@ public class PlayerMovement : MonoBehaviour

private Vector2 previousMovement = Vector2.zero;

private string socketUrl;
async void Start()
{
try
{
var uri = new Uri("http://localhost:3000");
env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
var uri = new Uri(socketUrl);
clientSocket = new SocketIOUnity(uri);

await clientSocket.ConnectAsync();
Expand Down
127 changes: 108 additions & 19 deletions Assets/Scripts/Trap/TrapManager.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,151 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using SocketIOClient;
using Newtonsoft.Json.Linq;
using CandyCoded.env;

public class TrapManager : MonoBehaviour
{

public List<GameObject> trapPrefabs = new List<GameObject>();
private Dictionary<string, GameObject> trapPrefabDictionary = new Dictionary<string, GameObject>();
private int gridSizeX = 9;
private int gridSizeY = 9;
private string[,] grid;

private Queue<TrapPlacement> placementQueue = new Queue<TrapPlacement>();
private SocketIOUnity clientSocket; // SocketIO client

private string socketUrl;

void Start()
{

// Initialize the grid
grid = new string[gridSizeX, gridSizeY];


// Map trap names to their prefabs
trapPrefabDictionary.Add("crossbow_down_prefab", trapPrefabs[0]);
trapPrefabDictionary.Add("crossbow_up_prefab", trapPrefabs[1]);
trapPrefabDictionary.Add("crossbow_side_prefab", trapPrefabs[2]);

// Exemple
SpawnTrapAtPosition(3, 5, "crossbow_down_prefab");
// Set up Socket.IO client
SetupSocket();
StartCoroutine(ProcessPlacementQueue());
}

async void SetupSocket()
{
try
{
env.TryParseEnvironmentVariable("SOCKET_URL", out string socketUrl);
var uri = new Uri(socketUrl); // Replace with your backend URL
clientSocket = new SocketIOUnity(uri);

public void SpawnTrapAtPosition(int x, int y, string trapType)
// Connect to the server
await clientSocket.ConnectAsync();

Debug.Log("Connected to backend and listening for trap placement events.");
}
catch (Exception e)
{
Debug.LogError("Socket connection error: " + e.Message);
}
}

public void Update()
{
clientSocket.On("traps:place", response =>
{
JArray trapDataArray = JArray.Parse(response.ToString());

foreach (var trapData in trapDataArray)
{
JObject trap = (JObject)trapData["trap"];

int x = trap["x"].Value<int>();
int y = trap["y"].Value<int>();
string trapType = trap["trapType"].Value<string>();

EnqueuePlacementOrder(x, y, trapType);
}
});
}

private void EnqueuePlacementOrder(int x, int y, string trapType)
{
placementQueue.Enqueue(new TrapPlacement(x, y, trapType));
}

private IEnumerator ProcessPlacementQueue()
{
while (true)
{
if (placementQueue.Count > 0)
{
TrapPlacement placement = placementQueue.Dequeue();
SpawnTrapAtPosition(placement.x, placement.y, placement.trapType);
}

yield return null; // Wait for the next frame
}
}

private void SpawnTrapAtPosition(int x, int y, string trapType)
{

// Check if the coordinates are valid and the spot is not occupied
if (x >= 0 && x < gridSizeX && y >= 0 && y < gridSizeY && grid[x, y] == null)
{

if (trapPrefabDictionary.ContainsKey(trapType))

// Check if the trap type exists in the dictionary
if (trapPrefabDictionary.TryGetValue(trapType, out GameObject prefabToSpawn))
{
GameObject prefabToSpawn = trapPrefabDictionary[trapType];
if (prefabToSpawn != null)
{

Vector3 spawnPosition = new Vector3(x, y, 0);
Instantiate(prefabToSpawn, spawnPosition, Quaternion.identity);
// Instantiate the prefab at the calculated position
Vector3 spawnPosition = new Vector3(x, y, 0);
GameObject spawnedTrap = Instantiate(prefabToSpawn, spawnPosition, Quaternion.identity);


grid[x, y] = trapType;
// Mark the grid spot as occupied
grid[x, y] = trapType;
}
else
{
Debug.LogError($"Prefab for '{trapType}' is null! Check if the prefab is correctly assigned in the Inspector.");
}
}
else
{
UnityEngine.Debug.LogWarning($"Le type de prefab '{trapType}' n'existe pas.");
Debug.LogWarning($"The trap type '{trapType}' does not exist in the dictionary.");
}
}
else
{
UnityEngine.Debug.LogWarning($"Position ({x}, {y}) est d�j� occup�e ou hors de la grille.");
Debug.LogWarning($"Position ({x}, {y}) is either occupied or out of bounds.");
}
}

void OnApplicationQuit()
{
if (clientSocket != null)
{
clientSocket.Dispose(); // Properly close the connection
}
}

public void ReceivePlacementOrder(int x, int y, string trapType)
private class TrapPlacement
{
// M�thode pour recevoir des commandes WebSocket et placer les pi�ges
SpawnTrapAtPosition(x, y, trapType);
public int x;
public int y;
public string trapType;

public TrapPlacement(int x, int y, string trapType)
{
this.x = x;
this.y = y;
this.trapType = trapType;
}
}
}
2 changes: 2 additions & 0 deletions Packages/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"com.unity.2d.animation": "9.1.2",
"com.unity.2d.sprite": "1.0.0",
"com.unity.2d.tilemap": "1.0.0",
"com.unity.nuget.newtonsoft-json": "3.2.1",
"com.unity.ugui": "1.0.0",
"xyz.candycoded.env": "https://github.com/CandyCoded/env.git#v1.1.0",
"com.unity.modules.ai": "1.0.0",
"com.unity.modules.androidjni": "1.0.0",
"com.unity.modules.animation": "1.0.0",
Expand Down
9 changes: 8 additions & 1 deletion Packages/packages-lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
},
"com.unity.nuget.newtonsoft-json": {
"version": "3.2.1",
"depth": 1,
"depth": 0,
"source": "registry",
"dependencies": {},
"url": "https://packages.unity.com"
Expand All @@ -111,6 +111,13 @@
"com.unity.modules.imgui": "1.0.0"
}
},
"xyz.candycoded.env": {
"version": "https://github.com/CandyCoded/env.git#v1.1.0",
"depth": 0,
"source": "git",
"dependencies": {},
"hash": "c6951bc02488dbe99f48509a9e289ee73c74acda"
},
"com.unity.modules.ai": {
"version": "1.0.0",
"depth": 0,
Expand Down