waifu_anton
waifu_anton

Reputation: 53

How to set up acceleration in Unity2D?

I am doing my own "Dinosaur game" (like in Chrome) in Unity. My dinosaur, however, accelerates way too fast. Can you help me to find a problem in my code?

Here the code:

void FixedUpdate()
{
    rb2d.Cast(Vector2.down, hitBuffer);
    float distance = hitBuffer[0].distance;
    if (distance > minMoveDistance)
        Fall();
    else
        Move();
}

void Fall()
{
    transform.Translate(fall);
    fall += Physics2D.gravity * Time.fixedDeltaTime;
    fall = Vector2.ClampMagnitude(fall, 90 * Time.fixedDeltaTime);
}

void Move()
{
    transform.Translate(move);
    move.x += (acceleration * Time.fixedDeltaTime);
}

Upvotes: 0

Views: 3346

Answers (1)

Brian Choi
Brian Choi

Reputation: 753

public void Update()
{
    if (hasAcceleration)
    {
         // AddForce(Vector2 force, ForceMode2D mode = ForceMode2D.Force);
         // 
         rigidbody2D.AddForce(force, ForceMode2D.Force);
    }
}
  • or by your self,
public void AddForce(Vector3 force)
{
    Vector3 f = force;
    f = f / mass;
    acceleration += f;
}

public void AddForce(Vector2 force)
{
    AddForce(new Vector3(force.x, force.y, 0.0f));
}

public void UpdateMovement(float deltaTime)
{
    velocity += acceleration;
    acceleration *= 0;

    movement = velocity * deltaTime;

    transform.localPosition += movement;
}

Upvotes: 1

Related Questions