Why is this code not working?
It was working fine before I tried to add an animation. The animation didn't work so I just decided to figure it out later, I deleted everything that involved the animation from the script... then it stopped working! My player (a cube) goes straight through the walls, and when it touches the walls its suppose to stop being able to move in that direction. `using UnityEngine; using System.Collections;
public class Move : MonoBehaviour { public bool canUp = true; public bool canDown = true; public bool canLeft = true; public bool canRight = true;
void Update()
{
if (canUp == true)
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
transform.Translate(1f, 0f, 0f);
}
}
if (canDown == true)
{
if (Input.GetKeyDown(KeyCode.DownArrow))
{
transform.Translate(-1f, 0f, 0f);
}
}
if (canLeft == true)
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.Translate(0f, 0f, 1f);
}
}
if (canRight == true)
{
if (Input.GetKeyDown(KeyCode.RightArrow))
{
transform.Translate(0f, 0f, -1f);
}
}
}
void OnCollisionEnter(Collision wall)
{
if (wall.gameObject.tag == "TopWall")
{
canUp = false;
}
if (wall.gameObject.tag == "BottomWall")
{
canDown = false;
}
if (wall.gameObject.tag == "LeftWall")
{
canLeft = false;
}
if (wall.gameObject.tag == "RightWall")
{
canRight = false;
}
}
void OnCollisionExit(Collision wall)
{
if (wall.gameObject.tag == "TopWall")
{
canUp = true;
}
if (wall.gameObject.tag == "BottomWall")
{
canDown = true;
}
if (wall.gameObject.tag == "LeftWall")
{
canLeft = true;
}
if (wall.gameObject.tag == "RightWall")
{
canRight = true;
}
}
}
Never$$anonymous$$d! I figured it out! $$anonymous$$y player needed a rigidbody on it so that it would collide with the walls, but if there is an easier was to do this I would love to know.
Hi.
Glad you've sorted it out.
Take a look at GetAxis at this link: https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
I'd recommend searching for some tutorials on it if you aren't sure how to implement it in your game.
Good luck.
Your answer
