Login | Register

Strafing

April 4, 2007, 14:54 by Calle
[loading]
-->
I saw a question on this a while ago and I thought that I'd write a little about it. For those who don't know, strafing is when you move sidewards. This is common in FPS-view games and also top-down view. Look at my example, and imagine that the arrow is in fact a soldier. We steer with the mouse, but we do not want to have to change direction entirely just to pass an object or similar and that's when we use this. Anyhow, the problem from a programmer point of view is that we don't know what position is left/right to us, and therefore do not know how to change our position in order to make the character strafe. My movement for this example is direction orientated, and all I have to do is therefore a little alternation. First look at the code and then I'll explain.

Step Event:
execute code:

dir = point_direction(x,y,mouse_x,mouse_y);
image_angle = dir;
if keyboard_check(ord('A')) {
x -= lengthdir_x(4,dir-90);
y -= lengthdir_y(4,dir-90);
}
if keyboard_check(ord('D')) {
x -= lengthdir_x(4,dir+90);
y -= lengthdir_y(4,dir+90);
}
if keyboard_check(ord('S')) {
x -= lengthdir_x(4,dir);
y -= lengthdir_y(4,dir);
}
if keyboard_check(ord('W')) {
x += lengthdir_x(4,dir);
y += lengthdir_y(4,dir);
}


dir is the direction between the object (the center of the object, because of my sprite origin), and therfore when I move forward I want to go to some point in dir direction and x step. This can be calculated using the lengthdir functions, which is actually trigonometry. Look at the last piece of code, when "W" is pressed. Then I first assign x the value of x+4 in the given direction dir. In "S" I do the reverse where I have -4 instead of 4. If I want to strafe I will want to use the same speed, but different direction - since we do not any longer want to walk towards the mouse.

Imagine a cross with the four directios; and we go up. If we want to strafe sidewards then we want the directions on either one or the other side. 360/4 is 90, and therefore we know that is the difference between the angles and that's how we can't calculate the angle with either dir+90 or dir-90 ...

This wasn't very good explained, but you can always ask if you want to know something more. You can always try the example and see if that improves your understanding.

Example: http://gmtutorials.com/files/strafeexample.gm6

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games