向左或向右移动时翻转对象

问题描述 投票:0回答:1

愚蠢的问题,但我是新手 所以我试图制作一个 2d 游戏,其中玩家是屏幕底部的 2d 对象,收集掉落的东西,我试图让玩家看它移动的方向

我尝试过,但这不是我想要的

    void Update()
    {
        if(Input.GetMouseButton(0)) 
        {
            Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            if(touchPos.x < 0) 
            {
                rb.AddForce( Vector2.left * moveSpeed );
                transform.Rotate(new Vector4(0, 180, 0));
            }
            else
            {
                rb.AddForce(Vector2.right * moveSpeed );
                transform.Rotate(new Vector4(0, 180, 0));

            }

        }
        else
        {
            rb.velocity = Vector2.zero;
        }
    }
}
c# android unity-game-engine 2d-games
1个回答
0
投票

您应该确定移动方向,然后相应地设置旋转所以...

1-确定移动方向:您需要确定玩家是向左还是向右移动。这可以通过检查触摸或鼠标单击相对于玩家当前位置的位置来完成。

2- 设置旋转: 一旦知道移动方向,就可以设置播放器的旋转。在 2D 游戏中,这通常是通过翻转精灵而不是旋转对象来完成的。

void Update()
{
    if(Input.GetMouseButton(0)) 
    {
        Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = Vector2.right;

        if(touchPos.x < transform.position.x) 
        {
            // Moving left
            direction = Vector2.left;
            // Flip sprite to face left
            transform.localScale = new Vector3(-1, 1, 1);
        }
        else
        {
            // Moving right
            // Flip sprite to face right
            transform.localScale = new Vector3(1, 1, 1);
        }

        rb.AddForce(direction * moveSpeed);
    }
    else
    {
        rb.velocity = Vector2.zero;
    }
}

/*
Instead of rotating the object, I'm flipping the sprite by changing the local scale. If the player moves left, the x scale is set to -1 (flipped), and if moving right, it's set to 1 (normal) and direction of force added to the rigid body is determined by the position of the touch relative to the player's position
*/

© www.soinside.com 2019 - 2024. All rights reserved.