Question by
Arkonali · Jun 11, 2020 at 09:43 PM ·
movementgameobjectscripting beginner
Have a GameObject to move only horizontally and not vertically
Hi, so i'm doing a Sokoban like game, with boxes being pushed and all, and i want one kind of boxes to be pushable only horizontally, not vertically, my boxes are not using boxcollider2D, i'm moving them by using this code on their script :
public class OrangeBox : MonoBehaviour
{
public bool Move(Vector2 direction)
{
if (OrangeBoxBlocked(transform.position, direction))
{
return false;
}
else
{
transform.Translate(direction);
return true;
}
}
bool OrangeBoxBlocked(Vector3 position, Vector2 direction)
{
Vector2 newPos = new Vector2(position.x, position.y) + direction;
GameObject[] walls = GameObject.FindGameObjectsWithTag("Wall");
foreach (var wall in walls)
{
if (wall.transform.position.x == newPos.x && wall.transform.position.y == newPos.y)
{
return true;
}
}
GameObject[] blueboxes = GameObject.FindGameObjectsWithTag("BlueBox");
foreach (var box in blueboxes)
{
if (box.transform.position.x == newPos.x && box.transform.position.y == newPos.y)
{
return true;
}
}
return false;
}
}
With my player having this script :
public class Player : MonoBehaviour
{
public bool Move(Vector2 direction)
{
if (Mathf.Abs(direction.x) < 0.5)
{
direction.x = 0;
}
else
{
direction.y = 0;
}
direction.Normalize();
if (Blocked(transform.position, direction))
{
return false;
}
else
{
transform.Translate(direction);
return true;
}
}
I'm new to programming so please explain as much as you can on how to do it, and if you need more information feel free to ask. Thanks in advance ! :)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613000715im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making GameObject move in the direction of my mouse (3d) 0 Answers
Here how do I attach the gameObject to the Script in Unity? 2 Answers
air hockey problem with independent controls 0 Answers
Why does it starts going backwards. 0 Answers
Unable to have Input.GetButtonDown properly move my GameObject. 1 Answer