简体   繁体   中英

Unity stop diagonal movement using transform.position method

I'm having a ton of trouble trying to understand how to stop my Ball objects from moving diagonally when they are swiped left or right, essentially what happens is: I swipe a ball in a direction, and the ball falls from the top of the screen. When i swipe the Ball it moves left and right but it also falls slightly still because of the downwards movement - how do i change this ? My game is 2D

Here is all the code you should need

//Variables 
public float ballSpeed = 10; //This will handle our Balls left and Right movement when swiped
public float fallSpeed = 2;  //This will handle the speed at which our ball falls
[HideInInspector]
public bool hitWall = false; //Check if our ball has collided with a wall
public bool moveRight, moveLeft;

public RoundHandler roundHandler;


private void OnEnable()
{
    //Get our Components 
    roundHandler = FindObjectOfType<RoundHandler>();
}

#region functions 

void checkWhereToMove()
{
    if (moveLeft == true)
    {
        transform.position -= transform.right * Time.deltaTime * ballSpeed;

    }

    if (moveRight == true)
    {
        transform.position += transform.right * Time.deltaTime * ballSpeed;

    }
}

public void moveDown() {

    //Set our Fall Speed modified by our Current rounds
    fallSpeed = roundHandler.ballFallSpeed;

    if (hitWall != true) {
        //Check if we arnt moving left or Right so that we can move down
        if (moveLeft == false || moveRight == false)
        {
            //Move our Ball down 
            transform.position -= transform.up * Time.deltaTime * fallSpeed;
            //Get our movement input
            checkWhereToMove();
        }    
    } 
}
#endregion

private void FixedUpdate()
{
    moveDown();
}
  1. Testing for movement requires checking to see if both directions are false.

  2. checkWhereToMove() is in the wrong place.

  3. After moving down, both directions need to be reset to false.

public void moveDown() {
        //Set our Fall Speed modified by our Current rounds
        fallSpeed = roundHandler.ballFallSpeed;

        //Get our movement input
        checkWhereToMove();

        if (hitWall != true) {
            //Check if we arnt moving left or Right so that we can move down

            if (moveLeft == false && moveRight == false) {
                //Move our Ball down
                transform.position -= transform.up * Time.deltaTime * fallSpeed;

                //Reset left and right movement
                moveLeft = false;
                moveRight = false;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM