Reputation: 1
SO i'm a beginner in programming and i need help with how to make my sprites speed increase (Add a sprint feature)
i have tried myself but i failed, if someone could explain how i could do it i would be very grateful.
All i want done is if i press the right trigger on my Xbox controller while moving my left thumb stick right change the speed from 4 to 6.
This is the thing i tried , i realized this wouldn't work because it would just make the sprite move when i press he trigger.
if (pad1.Triggers.Right < 0.0f)
position += new Vector2(-6, 0);
if (pad1.Triggers.Right >= 0.4f)
position += new Vector2(6, 0);
I'm out of options so someone please help.
Upvotes: 0
Views: 799
Reputation: 21245
This is fundamentally a physics problem. Adding a constant amount to the position is only going to move the sprite more. What you're probably looking for is a way to increase the velocity over brief a period of time which is known as acceleration.
const float AccelerationForce = 0.ff;
const float MaxAccelerationForce = 0.8f;;
static readonly Vector2 MaxAcceleration
= new Vector2(MaxAccelerationForce, MaxAccelerationForce);
static readonly Vector2 Acceleration = new Vector2(AccelerationForce, 0);
static readonly Vector2 Deceleration = new Vector2(-AccelerationForce, 0);
Vector _currentAcceleration = new Vector2(0, 0);
Vector _currentVelocity = new Vector2(0, 0);
Vector2 Clamp(Vector2 value, Vector2 min, Vector2 max)
{
var x = MathHelper.Clamp(value.X, min.X, max.X);
var y = MathHelper.Clamp(value.Y, min.Y, max.Y);
return new Vector2(x, y);
}
bool RequiresAcceleration(float currentForce)
{
return currentForce >= AccelerationForce;
}
var currentForce = GetCurrentForce();
// Calculate whether we need to accelerate or decelerated
var acceleration = RequiresAcceleration(currentForce)
? Acceleration
: Deceleration;
var newAcceleration = _currentAcceleration + acceleration;
// acceleration is bounded MaxAcceleration > _currentAcceleration > 0
_currentAcceleration = Clamp(newAcceleration, Vector2.Zero, MaxAcceleration);
_currentVelocity += _currentAcceleration;
// Code to move the player
if (pad1.Triggers.Right < 0.0f)
position += _currentVelocity);
if (pad1.Triggers.Right >= 0.4f)
position -= _currentVelocity;
Upvotes: 1
Reputation: 2192
I believe this is what you are trying to achieve. Also editing a post is rather easy please edit posts rather than commenting with an update.
if (pad1.Triggers.Right < 0)
// This checks if left thumbstick is less than 0.
// If it is less than zero it sets position.X += -6.
// If it is not less then it sets position.X += -4.
position.X -= (pad1.ThumbSticks.Left.X < 0) ? 6 : 4;
else if (pad1.Triggers.Right >= 0.4f) // shouldn't this be > 0.0f or > 0 ?
// This is the same as above just in the right direction.
position.X += (pad1.ThumbSticks.Left.X > 0) ? 6 : 4;
Upvotes: 0