Home > Blockchain >  Smoothing player movement and speed
Smoothing player movement and speed

Time:03-17

I know this question is already asked a few times, but didn't find it in the way of my code. In the movement of my playerObject I consider the direction the Camera is looking to atm. What I want to do is to slow down the speed of the movement, but it doesn't work with the walkSpeed I use. I also want to smooth the movement (start and end).

public void UpdateMovement()
{
    Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); //In targetDir the direction the Player wants to move to is saved -> player presses W means forward
   // targetDir = Vector2.ClampMagnitude(targetDir, 1);

    Vector3 camForward = cam.forward;                                                              //camForward saves the direction, the cam is looking actually
    Vector3 camRight = cam.right;                                                                  //camRight saves the actual right side of the cam     

    camForward.y = 0.0f;                                                                           //y=0 because we don't want to fly or go into the ground
    camRight.y = 0.0f;
    camForward = camForward.normalized;
    camRight = camRight.normalized;

    transform.position  = (camForward * targetDir.y   camRight * targetDir.x) * walkSpeed * Time.deltaTime;

CodePudding user response:

I'm not sure exactly about what the context of what you're trying to do here is, but I think you're looking for Vector2.Lerp().

The way you use it is to first calculate a target position as a Vector. So,

Vector2 target = new Vector2(targetX, targetY)

I'll let you figure out what targetX and targetY are, based on wherever you're trying to move the thing you're moving.

Then you would come up with the speed, which is what you're pretty much already doing. Like so:

float speed = walkSpeed * Time.deltatime;

Finally, instead of setting the position directly, you use the Lerp function instead.

transform.position = Vector2.Lerp(transform.position, target, speed);

I didn't test any of this, and just wrote it on the fly, but I'm pretty sure this is what you're looking for.

CodePudding user response:

I wrote a script you can try to create a cube, I'm sorry because I'm also a unity3d newbie, but I hope it helps you

private Transform player;

Vector3 toposition;//interpolation

 void Start(){
      player = this.transform;
      toposition = new Vector3(0,5,0);
 }

  // Start is called before the first frame update
 void Update(){
       if(Input.GetKey(KeyCode.W)){
            UpdateMovement();
       }
 }

public void UpdateMovement(){
     
     player.transform.position = Vector3.Lerp(transform.position, toposition, Time.deltaTime * 5f);
}
  • Related