George
George

Reputation: 45

Player Movement with Velocity

I have a little question. I have a script that I attach to a GameObject and with it I can control the object up and down at a certain speed. I want the movement to be a little inertia, that is, to be more real. This is my code:

float moveSpeed = 5f;
void Update()
{
    float y = Input.GetAxisRaw("Vertical");
    Vector2 direction = new Vector2(0, y).normalized;
    Move(direction);
}

void Move(Vector2 direction)
{
    Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
    Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));
    Vector2 pos = transform.position;       
    pos += direction * moveSpeed * Time.deltaTime;
    pos.y = Mathf.Clamp(pos.y, min.y, max.y);
    transform.position = pos;       
}

This code works but seems unreal, it would be good to add some inertia or velocity. Help please!

Upvotes: 0

Views: 1257

Answers (2)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

Should be an easy fix:

Instead of accelerating from 0 to moveSpeed instantly, use Vector2.MoveTowards to slowly accelerate towards your target speed.

public float moveSpeed = 5f;
public float acceleration = 1f;
private Vector2 moveDirection = Vector2.zero;

void Update()
{
    float y = Input.GetAxisRaw("Vertical");
    Vector2 direction = new Vector2(0, y).normalized;
    Move(direction);
}

void Move(Vector2 direction)
{
    moveDirection = Vector2.MoveTowards(moveDirection, direction, 
        acceleration * Time.deltaTime);

    Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
    Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));
    Vector2 pos = transform.position;
    pos += moveDirection * moveSpeed * Time.deltaTime;
    //pos.y = Mathf.Clamp(pos.y, min.y, max.y);
    transform.position = pos;
}

Upvotes: 1

rs232
rs232

Reputation: 1317

If you want to change velocity, you need to change moveSpeed (which is your velocity), not just direction.

float moveSpeed = 0f;
// modify this to change how your intertia looks like
float frictionValue = 1f;
void Update()
{
  float y = Input.GetAxisRaw("Vertical");
  moveSpeed += y * Time.deltaTime;
  Move();
  moveSpeed = Mathf.Lerp(moveSpeed, 0f, frictionValue * Time.deltaTime); 
}
void Move()
{
  Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));
  Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));
  Vector2 pos = transform.position;       
  pos.y += moveSpeed * Time.deltaTime;
  pos.y = Mathf.Clamp(pos.y, min.y, max.y);
  transform.position = pos;       
}

Upvotes: 1

Related Questions