Sign in to follow this  

combining strafe and walk?

This topic is 1456 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all,

 

I've noticed that in my camera movement, when the camera/ player both walks forward/backward and strafes, the camera moves twice the amount as it should. At least that's what I think.

 

Below the code I'm using right now.

 

I have 2 questions:

- is my assumption correct that with the approach below, moving forward/backward + strafe at the same time, moves the camera/player twice the amount it should

- my approach to fix this, would be to check if the keys for both moving forward/backward and strafe and down, and if so, call a separate/ new function, moving the camera for strafe/ moving at once (if both keys down), if else only one etc.

 

What do you think?

			if(_dinput.KeyDown(DIK_W)) _player.SetPosition(_d3dcam.MoveForwardBackward(_timer.GetDelta() * _player.GetWalkSpeed()));
			if(_dinput.KeyDown(DIK_S)) _player.SetPosition(_d3dcam.MoveForwardBackward(_timer.GetDelta() * -_player.GetWalkSpeed()));		

			if(_dinput.KeyDown(DIK_A)) _player.SetPosition(_d3dcam.MoveLeftRight(_timer.GetDelta() * -_player.GetStrafeSpeed()));
			if(_dinput.KeyDown(DIK_D)) _player.SetPosition(_d3dcam.MoveLeftRight(_timer.GetDelta() * _player.GetStrafeSpeed()));


// the actual camera functions

/**************************************************************************************/
/***							MOVE FORWARD BACKWARD								***/
/*** ==> usage: when camera moves forward or backward								***/
/*** ==> calculates the changed X and Z camera position, based on movement value	***/
/**************************************************************************************/

VECTOR3 CD3dcam::MoveForwardBackward(const float pAmount)	
{ 
	mPosition += mLook * pAmount;					// 'flying' allowed, 6 DOF
	
	// to disable 'FLYING', use:
//	mPosition += D3DXVECTOR3(mLook.x, 0.0f, mLook.z) * pAmount;

	return VECTOR3(mPosition.x, mPosition.y, mPosition.z);
}

/**************************************************************************************/
/***							MOVE LEFT RIGHT										***/
/*** ==> usage: when camera strafes to the left or right							***/
/*** ==> calculates the changed X and Z camera position, based on movement value	***/
/**************************************************************************************/

VECTOR3 CD3dcam::MoveLeftRight(const float pAmount)
{
	mPosition += mRight * pAmount;

	return VECTOR3(mPosition.x, mPosition.y, mPosition.z);
}

Share this post


Link to post
Share on other sites
You're just adding two orthogonal vectors.  So you'll see sqrt(walk * walk + strafe * strafe) total movement speed.  If walking and strafing speeds are the same, this is sqrt(2) or about 1.4 times faster than normal.
 
If you want to limit your speed, instead of applying each movement directly to mPosition, make a temporary movement vector first, apply all your player inputs to it, then limit that vector's length just before adding it to mPosition.
 
 
movementVector = zero;
 
apply all input to the movementVector;
 
speed = length of movementVector;
 
if (speed > limit) // assuming limit > 0 to prevent divide-by-zero.
  movementVector = movementVector * (limit / speed);
 
mPosition += movementVector;
(edit) Note: You can also move the _timer.GetDelta() so that you only multiply it with movementVector on the final line. This way you won't need to multiply it with every vector, speed, or limit during your calculation. Edited by Nypyren

Share this post


Link to post
Share on other sites

I suspect you are correct, and your idea to fix it would work.

 

It's basically that velocity vector generated from strafe + movement is greater than the one generated by either one by itself.  

 

Heh @Nypyren beat me to it, and explained it better =)

Edited by ferrous

Share this post


Link to post
Share on other sites

That was easy, think I've got it.

Here it is, result looks as expected.

 

I've left the separate move forward/backward, left/right and up/down functions unchanged.

 

What do you think?

			Crealysm_math::VECTOR3 movement = Crealysm_math::VECTOR3(0.0f, 0.0f, 0.0f);

			if(_dinput.KeyDown(DIK_W)) movement.z =  _player.GetWalkSpeed();
			if(_dinput.KeyDown(DIK_S)) movement.z = -_player.GetWalkSpeed();
			
			if(_dinput.KeyDown(DIK_A)) movement.x = -_player.GetStrafeSpeed();
			if(_dinput.KeyDown(DIK_D)) movement.x = _player.GetStrafeSpeed();

			if(_dinput.KeyDown(DIK_PRIOR)) movement.y = _player.GetWalkSpeed();
			if(_dinput.KeyDown(DIK_NEXT)) movement.y = -_player.GetWalkSpeed();

			movement *= _timer.GetDelta();

			_player.SetPosition(_d3dcam.Move(movement));


VECTOR3 CD3dcam::Move(const Crealysm_math::VECTOR3 pMovement)
{
	MoveForwardBackward(pMovement.z);
	MoveLeftRight(pMovement.x);		
	MoveUpDown(pMovement.y);

	return VECTOR3(mPosition.x, mPosition.y, mPosition.z);
}

Share this post


Link to post
Share on other sites

That looks like it will work fine, but you will still have the ability to move faster than normal if you walk+strafe+climb at the same time.

 

It's totally optional if you want to limit the maximum movement speed or not.  If you do, use the idea in my pseudocode just before your "movement *= _timer.GetDelta()" line if you want to limit your combined XYZ speed, or before the PRIOR/NEXT keys if you only want to limit the XZ speed and not the Y speed.  For example, a game that allows the player to jump probably would do its speed limiting on the XZ movement and allow jumping/falling to let you move faster than what you can normally walk+strafe.

 

 

As a side note:  Another thing you can do with your new code is to cancel out opposite movements when the player presses both forward+back, left+right at the same time:  If you change each of the "=" to "+=" on each of your input checking lines, the opposite keys will cancel each other out when both buttons are pressed.

Share this post


Link to post
Share on other sites

Thanks Nypyren, got it.

The movement actually 'feels' smoother now.

 

Here's the result:

		if(!_d3dscene.GetAnimated())
		{
			_player.Running(_dinput.KeyDown(DIK_LSHIFT));
			Crealysm_math::VECTOR3 movement = Crealysm_math::VECTOR3(0.0f, 0.0f, 0.0f);

			if(_dinput.KeyDown(DIK_W)) movement.z +=  _player.GetWalkSpeed();
			if(_dinput.KeyDown(DIK_S)) movement.z += -_player.GetWalkSpeed();
			
			if(_dinput.KeyDown(DIK_A)) movement.x += -_player.GetStrafeSpeed();
			if(_dinput.KeyDown(DIK_D)) movement.x += _player.GetStrafeSpeed();

			if(_dinput.KeyDown(DIK_PRIOR)) movement.y += _player.GetWalkSpeed();
			if(_dinput.KeyDown(DIK_NEXT)) movement.y += -_player.GetWalkSpeed();

			movement.limit(_player.GetWalkSpeed());
			movement *= _timer.GetDelta();

			_player.SetPosition(_d3dcam.Move(movement));
		}

// NEW VECTOR3 inline function

	VECTOR3 limit(const float pMax)
	{
		if(x > pMax) x = pMax;
		if(y > pMax) y = pMax;
		if(z > pMax) z = pMax;
		return *this;
	}

Share this post


Link to post
Share on other sites


VECTOR3 limit(const float pMax)
{
   if(x > pMax) x = pMax;
   if(y > pMax) y = pMax;
   if(z > pMax) z = pMax;
   return *this;
}

The maximum operation applied on each dimension separately allows the diagonal speed still to be approx. 1.4 times greater than the maximum speed in a orthogonal direction. You have to limit the length of the vector, not its components. This is because the vector defines a velocity, i.e. a speed and a direction of motion, where the speed is its length.

Share this post


Link to post
Share on other sites

Ok. I might need some help on this. Do you mean I have to:

 

- calculate the length of the vector (sqrt(x*x + y*y + z*z)) = length

- if length > 'pMax', then make the vector the length of pMax

 

An example:

 

Movement vector = 0.5, 0.8, 0.5

Length/ magnitude = 1.067

 

Then I want to limit the vectors length to 'pMax', say 0.7.

I'm not sure how to do that, is this it?

 

Movement = 0.5, 0.8, 0.5 (1.067)

Limited = x, y, z (1.067)

 

New vector = movement * (0.7 / movement.length()

 

new.x = 0.5 * (0.7 / 1.067)

new.y = 0.8 * (0.7 / 1.067)

new.z = 0.5 * (0.7 / 1.067)

 

New = 0.33, 0.52, 0.33

Voila, magnitude = 0.7 smile.png

 

Is this it?

 

If so, I'll make an optimized version of the above as a (inline) function in my vector struct.

 

Ps.: this really helps brushing up vector math :)

Edited by cozzie

Share this post


Link to post
Share on other sites

This is called vector normalization. (Make vector length one)

 

normalize(V) = V / magintude(V)

 

So in your case: Vmove = normalize(V) * movespeed

Share this post


Link to post
Share on other sites

Okay, I'm not sure if I understand it correct then.

Wouldn't normalizing the vector mean it gets a length of 1.0 instead of the wanted 0.7 in this example?

Share this post


Link to post
Share on other sites

Just be careful you don't use the same limited vector for player movement as you do for things like gravity or getting flung by a catapult or whatever, as they should be normalized under a different set of constraints.  

 

Ie Don't do this:

playerVec += walkMovementVec

playerVec += gravityVec

 

playerVec= normalize(playerVec) * playerWalkSpeed

Share this post


Link to post
Share on other sites

Since you have different velocities in each direction it might be even better to scale after normalization, i.e.

if(_dinput.KeyDown(DIK_W)) movement.z += 1;
if(_dinput.KeyDown(DIK_S)) movement.z -= 1;
			
if(_dinput.KeyDown(DIK_A)) movement.x += 1;
if(_dinput.KeyDown(DIK_D)) movement.x -= 1;

if(_dinput.KeyDown(DIK_PRIOR)) movement.y += 1;
if(_dinput.KeyDown(DIK_NEXT)) movement.y -= 1;

movement = normalized(movement); // returns 0 if original length is 0, otherwise a unit vector is returned
movement.x *= _player.GetStrafeSpeed();
movement.y *= _player.GetWalkSpeed();
movement.z *= _player.GetWalkSpeed();
Edited by l0calh05t

Share this post


Link to post
Share on other sites

I've put the changes through, seems to work fine:

			Crealysm_math::VECTOR3 movement = Crealysm_math::VECTOR3(0.0f, 0.0f, 0.0f);

			if(_dinput.KeyDown(DIK_W)) movement.z += 1.0f; 
			if(_dinput.KeyDown(DIK_S)) movement.z -= 1.0f;
			
			if(_dinput.KeyDown(DIK_A)) movement.x -= 1.0f;
			if(_dinput.KeyDown(DIK_D)) movement.x += 1.0f;

			if(_dinput.KeyDown(DIK_PRIOR)) movement.y += 1.0f;
			if(_dinput.KeyDown(DIK_NEXT)) movement.y -= 1.0f;

			movement.normalize();
			movement.x *= _player.GetStrafeSpeed() * _timer.GetDelta();
			movement.y *= _player.GetWalkSpeed() * _timer.GetDelta();
			movement.z *= _player.GetWalkSpeed() * _timer.GetDelta();
			
			_player.SetPosition(_d3dcam.Move(movement));

Maybe a bit of topic, but can someone help me with the following.

I've made a inline normalize function for my vector struct, this works:

	VECTOR3 normalize()
	{
		float mag = sqrt(x*x + y*y + z*z);
		VECTOR3 normalized;
		normalized.x = x / mag;
		normalized.y = y / mag;
		normalized.z = z / mag;
		return normalized;
	}

But when I try this, it doesn't:

	VECTOR3 normalize()
	{
		float mag = sqrt(x*x + y*y + z*z);
		x = x / mag;
		y = y / mag;
		z = z / mag;
		return *this;
	}

What am I doing wrong?

Edited by cozzie

Share this post


Link to post
Share on other sites

I've put the changes through, seems to work fine:








			Crealysm_math::VECTOR3 movement = Crealysm_math::VECTOR3(0.0f, 0.0f, 0.0f);

			if(_dinput.KeyDown(DIK_W)) movement.z += 1.0f; 
			if(_dinput.KeyDown(DIK_S)) movement.z -= 1.0f;
			
			if(_dinput.KeyDown(DIK_A)) movement.x -= 1.0f;
			if(_dinput.KeyDown(DIK_D)) movement.x += 1.0f;

			if(_dinput.KeyDown(DIK_PRIOR)) movement.y += 1.0f;
			if(_dinput.KeyDown(DIK_NEXT)) movement.y -= 1.0f;

			movement.normalize();
			movement.x *= _player.GetStrafeSpeed() * _timer.GetDelta();
			movement.y *= _player.GetWalkSpeed() * _timer.GetDelta();
			movement.z *= _player.GetWalkSpeed() * _timer.GetDelta();
			
			_player.SetPosition(_d3dcam.Move(movement));

Maybe a bit of topic, but can someone help me with the following.
I've made a inline normalize function for my vector struct, this works:

	VECTOR3 normalize()
	{
		float mag = sqrt(x*x + y*y + z*z);
		VECTOR3 normalized;
		normalized.x = x / mag;
		normalized.y = y / mag;
		normalized.z = z / mag;
		return normalized;
	}

But when I try this, it doesn't:

	VECTOR3 normalize()
	{
		float mag = sqrt(x*x + y*y + z*z);
		x = x / mag;
		y = y / mag;
		z = z / mag;
		return *this;
	}
What am I doing wrong?


Various problems:

Consider what happens if movement is zero. 'mag' will be zero. You'll divide x, y, and z by zero - getting an undefined result (or an exception).

Also your line:

movement.normalize();

You're not using the return value, which is why the behavior of your two normalize methods differ. The first normalize method will not change 'this', and you're not using the return value, so it doesn't actually do anything right now. Both methods can divide-by-zero, but the second one will actually be used because it changes 'this' itself.


Also, consider what normalizing a vector does: It FORCES it to be length = 1, even if the length was less than 1. What if the player wants to move slower than that? What if they don't want to move at all? Let's say you have an analog joystick instead of keys. The possible x/y inputs from the joystick are a continuous range from zero to maximum movement in each direction. Normalizing forces those to adhere to the points on the edge of a unit sphere, meaning you'll always move at maximum speed in SOME direction even if you don't want to.

Look at what I suggested in my first post:
 
if (speed > limit)
Essentially, this limits movement to anywhere inside the unit sphere, not just the edge of it. It protects from division by zero and amplified jitter when normalizing vectors that are extremely close to zero. Edited by Nypyren

Share this post


Link to post
Share on other sites

Thanks.

 

- I understand what you mean with the division by 0, strange thing is that it isn't crashing when I don't move, even when I initially start up the demo/ application

Action: I could check if mag != 0 and only if so, proceed. Is that the way to go?

 

- OK, so my second normalize function of my vector struct is the right way to go. I'll use that and see what it's going wrong, probably because of the division by zero :)

 

- I read back your earlier reply/ post and I'm chewing on it (again)

 

I'll let you know when it's finished and I understand it :)

Share this post


Link to post
Share on other sites

Think I've got it, results below.

To make sure I understand correct, I think this is what I'm doing:

 

1. creating a zero vector

2. get keyboard input to determine the base movement

3. based on the magnitude of the vector, 'limit' the movement (over all axes now) to my max walking speed * delta

4. update the position of the camera and player

 

A few thoughts:

- DeltaT is now multiplied when 'limiting', I could also do that in the end when updating the position (difference?)

- If I wanted to distinguish walking/ strafing/ 'flying' speed I could copy this line three times, using a different 'walkspeed':

movement = movement * ((_player.GetWalkSpeed() * _timer.GetDelta()) / speed);

- "Movement = movement *" can also be "movement *=" smile.png

 

I don't think distinguishing walking and strafe speed is necessary anymore, since I introduced it as a hack to prevent walking + strafing to be to quick smile.png)

 

I also remade my vector functions, I'll split it to a separate header with the prototypes and move the implementations to a new cpp file

(it's growing too large, I'll also have to add more operations, !=, == etc.).

			_player.Running(_dinput.KeyDown(DIK_LSHIFT));	
			Crealysm_math::VECTOR3 movement = Crealysm_math::VECTOR3(0.0f, 0.0f, 0.0f);

			if(_dinput.KeyDown(DIK_W)) movement.z = 1.0f; 
			if(_dinput.KeyDown(DIK_S)) movement.z = -1.0f;
			
			if(_dinput.KeyDown(DIK_A)) movement.x = -1.0f;
			if(_dinput.KeyDown(DIK_D)) movement.x = 1.0f;

			if(_dinput.KeyDown(DIK_PRIOR)) movement.y = 1.0f;
			if(_dinput.KeyDown(DIK_NEXT)) movement.y = -1.0f;

			float speed = movement.magnitude();
			if(speed > _player.GetWalkSpeed())
				movement = movement * ((_player.GetWalkSpeed() * _timer.GetDelta()) / speed);

			_player.SetPosition(_d3dcam.Move(movement));


// a few of the vector functions

	// RETURN MAGNITUDE OF VECTOR
	float magnitude()
	{
		return sqrt(x*x + y*y + z*z);
	}

	// NORMALIZE THE VECTOR IF MAGNITUDE != 0
	VECTOR3 normalize()
	{
		float mag = sqrt(x*x + y*y + z*z);
		if(mag != 0.0f)
		{
			x = x / mag;
			y = y / mag;
			z = z / mag;
		}
		return *this;
	}

	// MULTIPLY A VECTOR WITH A SCALAR
	VECTOR3 operator* (const float pScalar)
	{
		VECTOR3 newVector = *this;
		newVector.x *= pScalar;
		newVector.y *= pScalar;
		newVector.z *= pScalar;
		return newVector;
	}

Edited by cozzie

Share this post


Link to post
Share on other sites
Almost! Most of it looks good.

Right now there's just one problem that I see: Your units of measure are inconsistent. By "units of measure", I mean:

When your movements are being made by input keys, the units-of-measure are unitless.

When you multiply by your walking speed, you convert your unitless value to a distance-per-second value.

When you multiply your distance-per-second value by the time delta, time delta is a seconds-per-frame value, so your result is a distance-per-frame value.

Having different units of measure in different steps of the calculation is fine, you just need to make sure each math expression is consistent.

When you compare, add, or subtract different values, you need to make sure they're using the same units of measure, or the operation won't make sense.

Here's what I would do:
 
movement = movement * _player.GetWalkSpeed(); // converts movement from unitless to distance-per-second.

float speed = movement.magnitude();

if(speed > _player.GetWalkSpeed()) // distance-per-second vs. distance-per-second
    movement = movement * _player.GetWalkSpeed() / speed; // distance-per-second * (distance-per-second / distance-per-second) => distance-per-second

movement = movement * _timer.GetDelta(); // converts distance-per-second to distance-per-frame.
If you want to have different walking/strafing/flying speeds, then you could do it kind of like you were saying, except leave the time delta part off.

I would always do the GetDelta part at the very end because that always needs to be done, only needs to be done once, and doesn't need to happen before the speed limit check. Putting it at the end means all your other calculations can be done in distance-per-second instead of needing to convert back and forth between distance-per-second and distance-per-frame.

Reference: http://en.wikipedia.org/wiki/Units_of_measurement#Guidelines Edited by Nypyren

Share this post


Link to post
Share on other sites

I fully get it, thanks for the clear explanation.

All set to go, just did the changes and 'written them out' to make sure I understand.

 

Always using the same units of measure in the end, will definately give me flexibility for the future and prevents confusion and nasty bugs (thus saves time).

 

I removed the whole separate strafe speed, because I don't need it anymore. Keeping the code clean :)

Share this post


Link to post
Share on other sites
Sign in to follow this