【问题标题】:Right paddle not moving in pong game for unity为了团结,右桨在乒乓球比赛中不动
【发布时间】:2016-04-25 01:49:12
【问题描述】:

我试图让玩家在乒乓球比赛中控制两个球拍。然而,由于某种原因,只有一个桨是可控的,而另一个则根本不做任何事情。这是 paddle 属性栏的图像。

这是最右边的代码,应该用箭头键控制。

    using UnityEngine;

使用 System.Collections;

公共类 PaddleRight : MonoBehaviour {

public Vector3 playerPosR;
public float paddleSpeed = 1F;
public float yClamp;
void Start()
{


}

// Update is alled once per frame
void Update()
{

    float yPos = gameObject.transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);

    if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow)) {
        playerPosR = new Vector3(gameObject.transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
        print("right padddle trying to move");
    }

    gameObject.transform.position = playerPosR;
}

}

我似乎无法弄清楚为什么它不会移动。请,任何帮助都会很棒,因为此时我已经检查了所有地方。谢谢!

【问题讨论】:

    标签: c# scripting unity3d


    【解决方案1】:

    我在一个项目中重新创建了该问题,发现唯一的问题可能是您忘记了 yClamp 是公共的并且在检查器中设置为 0。确保将 yClamp 设置为应为的值,而不是 0。

    我建议移动 yPos 分配以及在 if 语句中设置位置,因为如果玩家没有移动,则不会更改这些位置。

    您也可以将gameObject.transform.position 更改为纯transform.position

    这里是精炼的代码:

    public Vector3 playerPosR;
    public float paddleSpeed = 1F;
    public float yClamp; // make sure it's not 0 in the inspector!
    
    // Update is alled once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.UpArrow))
        {
            float yPos = transform.position.y + (Input.GetAxis("Vertical") * paddleSpeed);
            playerPosR = new Vector3(transform.position.x, Mathf.Clamp(yPos, -yClamp, yClamp), 0);
            transform.position = playerPosR;
        }
    }
    

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多