I’m totally new to Unity, so this question might sound silly. I’m working on a custom “collision” system. When the player presses an arrow key, the code checks to make sure the “player” block is not right up against a “wall” block (both the “player” and “wall” blocks have dimensions 1x1x1), and if it is not, it moves 1 unit in the specified direction (x and z movement only).
I created a “player” cube and a “wall” cube in my scene, attached the script to the “player” cube, dragged the respective components from the hierarchy to the inspector, and tested it out. It worked great! However – I then turned the “wall” cube into a prefab, and made another one, identical to the first, moved it by a few units so it wouldn’t be in the same position, and tried again. My “player” cube moved right through this one, but still wouldn’t move through the other one.
I can only assume the problem is that my code doesn’t say anything about applying this script to multiple “walls”, and thus will only work on one, even if they’re exact duplicates of each other.
My question is: How can I get this script to apply to all 1x1x1 “wall” blocks I create, instead of working for one and totally ignoring all the others? Thanks in advance for any help! Sorry if this is too simple a question.
var player : Transform;
var wall : Transform;
var speed : float = 5;
while(true) yield CoUpdate();
function CoUpdate() {
if (Input.GetKey(KeyCode.RightArrow)
&& (player.position.x + 1 != wall.position.x
|| player.position.z != wall.position.z))
yield Move(Vector3.right);
if (Input.GetKey(KeyCode.LeftArrow)
&& (player.position.x - 1 != wall.position.x
|| player.position.z != wall.position.z))
yield Move(Vector3.left);
if (Input.GetKey(KeyCode.UpArrow)
&& (player.position.z + 1 != wall.position.z
|| player.position.x != wall.position.x))
yield Move(Vector3.forward);
if (Input.GetKey(KeyCode.DownArrow)
&& (player.position.z - 1 != wall.position.z
|| player.position.x != wall.position.x))
yield Move(Vector3.back);
else
yield;
}
function Move(distance : Vector3) {
var pt = player.transform;
var goal = pt.position + distance;
while (pt.position != goal) {
pt.position = Vector3.MoveTowards(pt.position, goal, speed * Time.deltaTime);
yield;
}
}