- Home /
How to get a rigidbody2d's actual speed?
In a runner game I'm making I need to make the camera follow the player to follow the player (ball). If the player slows down because of any reason the camera starts moving independently. When the player reaches full speed again the camera lerps back to the player's position. The player is moves by a physical force applied every FixedUpdate. I want to do that by checking the actual speed (not the speed I'm adding as a force to the player, but the actual speed it moves in) and then checking if it's slower than the full speed. The problem is that I don't know how to get the player's actual speed. How do I do that/Get around that? The code looks something like this: enum CameraFollowingStates {Following, Independent, Staying};
private void Update()
{
//change states
//Staying ==> Following
if(followingState == CameraFollowingStates.Staying && transform.position.x - followingX <= target.transform.position.x)
followingState = CameraFollowingStates.Following;
//Following ==> Independent
else if(followingState == CameraFollowingStates.Following &&/*actual speed of the ball less than full*/)
followingState = CameraFollowingStates.Independent;
//Independent ==> Staying
else if(followingState == CameraFollowingStates.Independent &&/*actual speed is full*/)
followingState = CameraFollowingStates.Staying;
//act based on state
switch(followingState)
{
case CameraFollowingStates.Following:
Vector3 temp = transform.position;
temp.x = target.transform.position.x + followingX;
transform.position = temp;
break;
case CameraFollowingStates.Independent:
transform.Translate(independentSpeed * Time.deltaTime, 0, 0);
break;
//in case it's Staying the camera doesn't move so nothing needs to be done.
}
}
Thanks in advance.
float playerSpeed;
playerSpeed = target.rigidbody2D.velocity.sqr$$anonymous$$agnitude;