1
\$\begingroup\$

I am looking for a sensible way to continuously move an object downwards with constant speed while moving left or right by some amount x when the user presses the left or right arrow keys.

Basically, movement should look like this:

|
|
V Right Arrow  Key pressed
    |
    |
    |
    V Right Arrow key pressed
        |
        |
        |
        V Left Arrow Key pressed
    |
    |
    |
    V

The movement on the x-axis should be smooth, i.e. it shouldn't jump from one spot to the next, but rather move to a specified x-coordinate slowly.

What I am having trouble with is moving along the x axis independently of the y-axis.

I have another project where I handled movement towards a certain goal with Vector2.MoveTowards

void Update()
{
    float step = 1 * Time.deltaTime;
    transform.position = Vector2.MoveTowards(transform.position, movementTarget, step);
}

I would use this by setting the object's movementTarget

But this doesn't lend itself to my current requirements because, when I set the movementTarget, I need to specify a y component, which leads the object's velocity on the direction to become zero once the movementTarget is reached, but I need the object to move continuously along the y-axis.

Basically, I am looking for a hypthetical method Vector2.MoveTowards that only takes an x-input.

I'm not sure if I'm making myself clear, so please ask questions if more information is needed.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Can you use Mathf.MoveTowards?

I believe it would be something like this:

var position = transform.position;
var step = velocity * Time.deltaTime;

position.x = Mathf.MoveTowards(position.x, targetX, step.x);
position.y = position.y + step.y;

transform.position = position;

Assuming you have a velocity vector, and velocity.x is positive (so step.X is also positive).

You would, of course, have to pick the targetX when you get the input. Perhaps something like this:

targetX = (direction + Mathf.Floor(transform.position.x / snap)) * snap;

Where snap is the non-zero horizontal step, and direction is -1.0f or 1.0f.

I don't know if you want to impose a minimum and maximum targetX. If you do, you might use Mathf.Clamp.

\$\endgroup\$
1
  • \$\begingroup\$ I was able to adapt your solution to make it work, thanks! \$\endgroup\$
    – ChrisC
    Commented Jul 22, 2023 at 20:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .