Home > other >  How to move a 2D object?
How to move a 2D object?

Time:09-27

I have three platforms, when a key is pressed, they should move to the right, and each platform should take the place of the other. Like a slider for example. The movement should be fast, but smooth. As an example: (only the animation is fast...) enter image description here

My code:

 if (Input.GetKeyDown("space"))
    {
        Vector2 move = new Vector2(rb.velocity.x   2f, rb.velocity.y);
        rb.velocity = Vector2.zero;
        rb.MovePosition(rb.position   move);
    }

I'm using RigidBody2D.MovePosition() but it works strictly and you can't see that the objects are moving.. the object should move to the right like RigidBody2D.AddForce() but stop like on animation.

CodePudding user response:

In order to move from one point to another, having animation like effects, I think it's better to use Lerp functions. Lerping means going from one point to the next, with a certain step, so if I lerp from 1 to 2 by a 0.1 step I end at 1.1. You can have constant step or use functions at here. Moreover, by using animation curves you can use your custom function. Add this sctipt to an empty GameObject, assign your squares and set speed. (This answer assumes you know the distance between each two squares.)

using System;
using System.Collections;
using UnityEngine;

public class Answer : MonoBehaviour
{
// your 3 squares 
[SerializeField] private Transform[] moves;
[SerializeField] private float speed = 1; 
private readonly Vector3 _offset = new Vector3(3.5f, 0, 0);
private bool _lerping;

private void Awake()
{
    _lerping = false;
}

private void Update()
{
    if (Input.GetKey(KeyCode.Space) && !_lerping)
    {
        foreach (var move in moves)
        {
            StartCoroutine(Move(move));
        }
    }
}

private IEnumerator Move(Transform move)
{
    _lerping = true;
    var initialPosition = move.position;
    var targetPosition = initialPosition   _offset;
    var distance = Mathf.Infinity;
    var t = 0f;

    while (distance > 0f)
    {
        // control how fast movement occurs
        t  = Time.deltaTime * speed;
        // use your own function for the third parameter
        move.position = Vector3.Lerp(initialPosition, targetPosition, EaseOutBounce(t));
        distance = Vector3.Distance(move.position, targetPosition);
        yield return null;
    }


    _lerping = false;
}

private static float EaseInExpo(float x) {
    return Math.Abs(x) < 0.01f ? 0 : Mathf.Pow(2, 10 * x - 10);
}

private static float EaseOutBounce(float x) {
    const float n1 = 7.5625f;
    const float d1 = 2.75f;

    if (x < 1 / d1) {
        return n1 * x * x;
    }

    if (x < 2 / d1) {
        return n1 * (x -= 1.5f / d1) * x   0.75f;
    }

    if (x < 2.5 / d1) {
        return n1 * (x -= 2.25f / d1) * x   0.9375f;
    }

    return n1 * (x -= 2.625f / d1) * x   0.984375f;
}}
  • Related