# Cant figure out auto-attack for platformer

A

#### A.J. Rich

##### Guest
Hey guys! ive been working on a platformer recently and i cant for the life of me figure out how to auto-attack enemies (moving quickly to the enemy hitbox point, which is y-16) when the player is near them and a certain key is pressed. below is a beautiful artistic example of what i mean:

heres the code i'm using for attacking right now in the enemies step event:

//enemy collision
if (place_meeting(x,y,obj_BLOB))
{
if (obj_BLOB.y < y-16){

with (obj_BLOB) vspd = -jspd;
hpts -= 1;
if (hpts = 0) {
instance_destroy();
}

}

else{

room_restart();

}
}

all the move_towards_point() and instance_nearest(x,y-16,obj_enemy) stuff ive tried has either caused the player to clip through the ground or flat out crashed the game. Any help would be greatly appreciated. Thank you!

#### SnotWaffle Studios

##### Member
Here's what I would do. Set up a variable called "attacking" that is true when you press your attack button, and false when it is done attacking. When pressing the attack button, calculate the vertical and horizontal speed necessary to jump onto the enemy from the current distance in a set amount of frames. For example:
Create Event:
Code:
``````attacking = false;
grav = .5; //Gravity during attack
hsp = 0; //Horizontal speed during attack
vsp = 0; //Vertical speed during attack
frames_of_attack = 20; //Change this to whatever number of frames you want the attack to be done in. The lower the number, the faster the attack
frames = 0;``````
Step Event:
Code:
``````if(attacking){
x+=hsp;
y+=vsp;
vsp+=grav;
if(frames<=0){
attacking = false;
vsp = 0;
hsp = 0;
}
frames-=1;
//This part might cause you to go through walls. You'll have to add checks for that so the attack stops
}else{
if(keyboard_check_pressed(vk_space)){ //Change vk_space to whatever your attack key is
enemy = instance_nearest(x,y,obj_enemy);
if(enemy!=noone){
attacking = true;
frames = frames_of_attack;
vsp = -frames*grav/2;
hsp = (enemy.x-x)/(frames*.95); //If your character is overshooting, change .95 to something higher (but below 1)
}
}
//Your other step event code should probably be in here so during an attack, nothing else can happen
}``````
This isn't an exact solution, but from my tests, it is good enough. It doesn't take into account differences in vertical position though. All that needs to be added is collision w/ enemy. When you collide with the enemy, make sure to set attacking to false so it doesn't make the player continue moving inside the enemy.

Let me know if you have any questions.

Last edited: