For Loop not working, collision problems
I am taking a Unity class in college and have run into a problem even my professor doesn't understand and can't solve. So I have a player Cube and I need obstacles/walls that the player can't move into. The issue is the if (manyObstacles[i] != newPos) line, newPos being the direction/position the player would move to. If the obstacle is NOT in the same position that the newPos would be, then allow the player to move to that spot. Even assigning the gameobjects in the Inspector does not work. I can get collision to work for one obstacle/wall but I can't do it for multiple. It works for my classmates. The professor said it's a logic issue. The Hazard part works fine. Any ideas?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class movement : MonoBehaviour
{ public TextMesh playerMSG; public Vector3 playerStart; float tileAmount = 1f; public Transform playerPiece; public Transform[] manyObstacles; public Transform[] manyHazards;
// Start is called before the first frame update
void Start()
{
playerStart = playerPiece.position;
}
// Update is called once per frame
void Update()
{
Vector3 newPos = playerPiece.position;
if(Input.anyKeyDown)
{
playerMSG.text = "find the key to advance";
}
// player movement
if (Input.GetKeyDown("left"))
{
newPos += new Vector3(-tileAmount, 0f, 0f);
}
if (Input.GetKeyDown("right"))
{
newPos += new Vector3(tileAmount, 0f, 0f);
}
if (Input.GetKeyDown("up"))
{
newPos += new Vector3(0f, 0f, tileAmount);
}
if (Input.GetKeyDown("down"))
{
newPos += new Vector3(0f, 0f, -tileAmount);
}
// obstacle and hazard functions
for (int i = 0; i < manyObstacles.Length; i++)
{
if (manyObstacles[i].position != newPos)
{
playerPiece.position = newPos;
}
}
for (int i = 0; i < manyHazards.Length; i++)
{
if (manyHazards[i].position == playerPiece.position)
{
playerPiece.position = playerStart;
}
}
} } }