2D movement with transform.translate and collision detection...?

Hi there, this might end up as a long question but I’ll try to provide as much information as possible.

I’m looking for a bit of help with collision detection.
I’m prototyping a 2D top down roguelike. At the moment I have a Player cube that can move up, down, left and right, one square at a time. Every time they move there is a chance to spawn an enemy from an enemyPrefab. If the enemy is within a certain distance of the player, the enemy will move towards the player one square at a time every time the player moves (every turn). This all works reasonably well but all movement is done with transform.translate.

At present the enemies will move towards the player and then come to occupy the same square as the player. What I would like them to do is stop in the adjacent square instead and then spend subsequent turns attacking the player, additionally if the player attempts to move onto the square occupied by the enemy I want them to instead attack the enemy. Once the enemy is dead the player can move over their square.

I’m assuming to do the things I want, I’m going to need collision detection, am I right? After doing some research it would appear that collision detection doesn’t seem to work with transform.translate, is that correct?

Does anyone have any advice for how I could proceed?

Thanks.

1 Answer

1

Check if the distance between the player’s position and the enemy’s position is equal to the distance for one square. This check will be different, depending on whether diagonal moves are legal, in your game. If they are, it should look something like this:

if(Vector2.Distance(transform.position, player.transform.position) > gridDistance)
{
    //move toward player
}

if diagonal movements are -illegal- (in other words, you only want the units moving along the cardinal directions), simply check distance like this:

float xDist = Mathf.Abs(transform.position.x - player.transform.position.x);
float yDist = Mathf.Abs(transform.position.y - player.transform.position.y);
if((xDist > gridDistance && yDist < 0.01f) 
    || (yDist > gridDistance && xDist < 0.01f))
{
    //move toward player
}

Your second suggestion works excellently for my enemies. They now stop in whatever player adjacent square they land in and i've added a debug log for the moment to say they're attacking. So thank you very much. My problem now is that if I move my player towards the enemy, they will land in the same square as the enemy. So would I be able to use oncollisionenter to block movement onto an enemy square and instead attack? Or do I need to find a different code solution for my player?