Unity使用transform.position方法停止对角线移动

时间:2017-10-07 01:27:01

标签: unity3d

我在试图理解如何在向左或向右滑动时阻止我的Ball物体沿对角线方向移动时遇到了很多麻烦,基本上会发生的事情是:我向一个方向滑动球,并且球从球落下屏幕上方。当我滑动球时它会左右移动但由于向下移动它也会略微下降 - 我该如何改变它?我的游戏是2D

以下是您需要的所有代码

//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 个答案:

答案 0 :(得分:1)

  1. 测试移动需要检查两个方向是否都是假的。

  2. checkWhereToMove()位置错误。

  3. 向下移动后,两个方向都需要重置为假。

  4. 
        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;
                }
            }
        }