Public Group

# Restricting 3D movement XNA c#

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

## Recommended Posts

Guys I was trying to get the basics down for my game and I can't seem to be able to restrict the characters movement on the X and Z axis. I have the following code:

// Prevent ship from flying under the ground
Position.Y = Math.Max(Position.Y, MinimumAltitude);

//Prevent ship from flying past the floor boundaries
Position.X = Math.Max(-650000.0f, 65000.0f);
Position.Z = Math.Max(-650000.0f, 65000.0f);

although this just stops the character from moving off this one spot.

One way I thought I could fix this is using some sort of sin or cos function to restrict its movement although how I would implement it is beyond me so any help would be really appreciated!

##### Share on other sites
Quote:
 Position.X = Math.Max(-650000.0f, 65000.0f);Position.Z = Math.Max(-650000.0f, 65000.0f);
I think you want to use a 'clamp' function here. The above two lines simply equate to:
Position.x = 65000.0f;Position.y = 65000.0f;

##### Share on other sites
Thanks a lot guys! :D

##### Share on other sites
Or you could just write:
Position.X = Math.Min(Math.Max(-650000.0f, Position.X), 65000.0f);
Position.Z = Math.Min(Math.Max(-650000.0f, Position.Z), 65000.0f);

##### Share on other sites
Quote:
 Original post by RatslayerOr you could just write:Position.X = Math.Min(Math.Max(-650000.0f, Position.X), 65000.0f);Position.Z = Math.Min(Math.Max(-650000.0f, Position.Z), 65000.0f);
If you're going to be performing this operation more than once (as is the case for the OP), you don't want to be writing that out or copy-and-pasting it repeatedly. Instead, the code should be factored out and placed in its own function so that it can be reused.

In other words, a 'clamp' function, as has already been suggested.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633702
• Total Posts
3013452
×