Home > Software engineering >  How to stop a Game Object after it reaches a certain position
How to stop a Game Object after it reaches a certain position

Time:12-27

I'm trying to figure out how to make my player stop when it reaches a certain position, but nothing seems to work. What I want is when the game object reaches a certain position that the game object will stop moving abruptly. I'm adding force to the RigidBody2d, so the game object moves and it evenly slows down, but I want it to just stop when it reaches a certain position. I'm trying to do this as a boundary restriction. I also tried using just a collider2D as the boundary, but still the game object just moves right threw it and the collider2D was not set as a trigger. This is for a mobile game, so I'm using the Touchscreen.

Here is what I have.

private void Update()
{
    MovePlayer();
}

private void MovePlayer()
{
    if (Touchscreen.current.primaryTouch.press.isPressed)
    {            
        Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(touchPosition);

        moveDirection = worldPosition - transform.position;
        moveDirection.z = 0f;
        moveDirection.Normalize();            
    }
    else
    {
        moveDirection = Vector3.zero;
    }

private void FixedUpdate()
{
    if (moveDirection == Vector3.zero) { return; }

    rb.AddForce(moveDirection * movementForce * Time.deltaTime, ForceMode2D.Force);
    rb.velocity = Vector3.ClampMagnitude(rb.velocity, velocity);

    if (transform.position.y >= 4f)
    {
        rb.velocity = Vector2.zero;
    }
}

CodePudding user response:

I think one of the issues might be the

if (moveDirection == Vector3.zero) { return; }

so if there is no user Input you don't ever reach the check for the position.

You should treat these separately.

private void FixedUpdate()
{
    var position = rb.position;

    if (position.y >= 4f)
    {
        rb.velocity = Vector2.zero;
        position.y = 4f;
        rb.position = position;
        return;
    }

    if (moveDirection == Vector3.zero) return;

    rb.AddForce(moveDirection * movementForce * Time.deltaTime, ForceMode2D.Force);
    rb.velocity = Vector3.ClampMagnitude(rb.velocity, velocity);       
}
  • Related