所以我试图找到一种方法,让玩家只需点击右箭头键就可以无限移动,如果它接触到另一个游戏对象,它就会停在游戏对象的位置,如果再次点击按钮,它就会再次移动。
注意:我刚开始使用unity,也刚开始用c#编程,所以请尽量用一种简单易懂的方式来解释。
代码如下:
Rigidbody2D rb2d;
public float speed = 10;
public const string RIGHT = "right";
public const string LEFT = "left";
string buttonPressed;
public GameObject Rainbow_1;
public GameObject Rainbow_0;
bool isCol = false;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKey(KeyCode.RightArrow)) { buttonPressed = RIGHT; }
else if (Input.GetKey(KeyCode.LeftArrow)) { buttonPressed = LEFT; }
else { buttonPressed = null; }
}
private void FixedUpdate()
{
if(buttonPressed == RIGHT)
{
if(isCol)
{
StartCoroutine(sfos());
}
else if(!isCol)
{
rb2d.velocity = new Vector2(speed, 0);
}
}
}
IEnumerator sfos()
{
Rainbow_0.transform.position = Rainbow_1.transform.position;
yield return new WaitForSeconds(3);
}
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Collision detected");
isCol = isCol;
}
private void OnCollisionExit2D(Collision2D other) { isCol = !isCol; }
发布于 2021-10-07 13:54:29
你想要做的是停止你的播放器:
rb2d.velocity = new Vector2(0, 0);
您还需要发出冲突信号:
isCol = true;
碰撞
在初始化之外的任何时刻,都不要将isCol
变量设置为true
。这意味着您的第一次冲突将会注册,但所有后续冲突将不会注册;要修复此问题,请更改:
private void OnTriggerEnter2D(Collider2D other) {
Debug.Log("Collision detected");
isCol = isCol;
}
private void OnCollisionExit2D(Collision2D other) { isCol = !isCol; }
至:
private void OnTriggerEnter2D(Collider2D other) {
Debug.Log("Collision detected");
isCol = true;
}
private void OnCollisionExit2D(Collision2D other) { isCol = false; }
当它像这样明确的时候更容易看出来。
速度
对于速度,您的FixedUpdate
方法有条件地将速度设置为speed, 0
,但您从未将其设置为其他任何值:
private void FixedUpdate() {
if(buttonPressed == RIGHT) {
if(isCol) {
StartCoroutine(sfos());
}
else if(!isCol) {
rb2d.velocity = new Vector2(speed, 0);
}
}
}
如果不想移动,则需要将速度设置为零;因此,如果isCol
为真:
private void FixedUpdate() {
if(buttonPressed == RIGHT) {
if(isCol) {
rb2d.velocity = new Vector2(0, 0);
StartCoroutine(sfos());
}
else if(!isCol) {
rb2d.velocity = new Vector2(speed, 0);
}
}
}
此外,为了简单起见,我相信Unity的2D向量包含一个名为zero
的属性/字段,因此以下内容也可以工作,但目前无法直接访问Unity,我不能承诺任何事情。
rb2d.velocity = Vector2.zero
https://stackoverflow.com/questions/69488034
复制相似问题