- Home /
How to detect objects near to the player
So, I'm new to unity and programming and I'm trying to make an 2D MMORPG with my friends. The game moviment will be tile per tile, like the old Pokemon and Tibia. The problem is that i made the player movement to be in a fixed distance (a tile) and when he enters collision the player gets stuck and I can't move him anywhere. I'm intending to make the player detect if there is any object in the direction that he will move, if so, he just don't move, without the need to use collision, do you have any idea how I can do that? Or is there any better solution for my problem?
My movement script:
public float speed;
Vector3 pos;
float sqm = 0.16f;
void Start()
{
pos = transform.position;
}
void Update()
{
}
void FixedUpdate()
{
if(Input.GetAxisRaw("Horizontal") > 0.001f && transform.position == pos)
{
pos += Vector3.right * sqm;
}
else if(Input.GetAxisRaw("Horizontal") < -0.001f && transform.position == pos)
{
pos += Vector3.left * sqm;
}
else if(Input.GetAxisRaw("Vertical") > 0.001f && transform.position == pos)
{
pos += Vector3.up * sqm;
}
else if(Input.GetAxisRaw("Vertical") < -0.001f && transform.position == pos)
{
pos += Vector3.down * sqm;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime * speed);
}
Answer by FlaSh-G · Aug 13, 2020 at 06:36 PM
Your solution will ultimately depend on how you implement your world, but the usual first way to go is putting colliders where your character isn't supposed to go, and when you do that, the Physics class will help you out. More specifically, the Raycast method is probably what you'll want to use.
Imagine it like an invisible laser pointer that tells you where it hits a collider. So you can cast a ray in the walking direction (and with a maxDistance of one tile width) and only when that ray hits nothing, the character is free to go there.
That seems good, I'll take a look on that. Thanks!
Answer by GoldenretriverYT · Aug 13, 2020 at 08:43 PM
I hope this MMORPG is not gonna be a big game, you should never start with big projects.
Well, if it is or isn't gonna be a good game I don't know, but I intend to learn with it :)