var NaturalSpeed = 10;
var tempSpeed : float;
var SpeedMultiplier = 1.2; // for 20% speed increase while sprinting
var moveDirection : Vector3; //this determines which direction we should be moving towards
function Update()
{
moveDirection = Vector3.zero; //this rests our move direction to nothing so we wouldn’t move unless movement keys were pressed
tempSpeed = NaturalSpeed; //this rests our speed back to natural speed
//this is just a simple movement check for demonstrating sprint; use your own methods of course
moveDirection.x += Input.GetAxis("Horizontal");
moveDirection.z += Input.GetAxis("Vertical");
if(Input.GetKey(KeyCode.LeftShift)) //this checks to see if the player is holding left shift
{
tempSpeed *= SpeedMultiplier; //this increases our speed by the multiplier
}
transform.Translate(moveDirection.normalized * tempSpeed * Time.deltaTime); //this moves our player to the correct direction at the determined speed (sprinted or not), smoothed over time
}
I will assume that the problem is that your speed is so fast that between two steps, you bypass the obstacle with the collider entirely.
Two ways to solve this:
-
Use physics, i.e, rigidbodies and forces instead of transform.Translate
-
This is “much” more involved, but I will summarize:
P = Previous position
C = Current position
At every frame, find P (I will assume you know how to find this). Find a bounding-box (BB) that will hold both the player at P, and C (you can use the encapsulate function). This BB basically is the path “carved out in space” by your player as it would move from P to C. Check if BB intersects with any obstacle. If it does, then assume an obstacle was hit while moving from P to C. Adjust the current position of your player accordingly*.
(Yes I know I have not explained “accordingly” as it is more involved, but I am not sure at this point whether the OP needs to know that detail).