在我的乒乓球游戏中,我希望它一旦击中碰撞机,它就会重置到默认位置。它确实会检测碰撞器和触发器。但是它不响应空格按钮
这是我的代码:
using UnityEngine;
using System.Collections;
public class BallControl : MonoBehaviour
{
public float speed = 10.0f;
private Rigidbody2D rbBall;
private Vector2 defaultPos;
void Start()
{
// Initial Velocity
GetComponent<Rigidbody2D>().velocity = Vector2.left * speed;
}
float hitFactor(Vector2 ballPos, Vector2 racketPos,
float racketHeight)
{
return (ballPos.y - racketPos.y) / racketHeight;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "Player1")
{
Debug.Log("P1 HIT!!!");
// Calculate hit Factor
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
// Hit the right Racket?
if (col.gameObject.name == "Player2")
{
Debug.Log("P2 HIT!!!");
// Calculate hit Factor
float y = hitFactor(transform.position,
col.transform.position,
col.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(-1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
}
public void reset (string startPosition)
{
transform.position = defaultPos;
rbBall = GetComponent<Rigidbody2D>();
if (startPosition == "Right")
{
rbBall.velocity = Vector2.right * 0;
if (Input.GetKeyDown(KeyCode.Space))
{
rbBall.velocity = Vector2.right * speed;
}
}
if (startPosition == "Left")
{
rbBall.velocity = new Vector2(-1,0) * 0;
if (Input.GetKeyDown(KeyCode.Space))
{
rbBall.velocity = new Vector2(-1,0) * speed;
}
}
}
}
编辑;所以这里它显示了我的控球脚本。这是我为参数设置的,这完全是我的代码。我希望它能够重置球的位置,按空格键恢复速度并继续游戏
它不起作用的原因仅仅是因为你在错误的地方使用了Input.GetKeyDown。据我所知,您的 Reset 方法只运行一次,这意味着玩家必须在与重置方法运行的完全相同的毫秒内单击空格键。
你想要的是将球部分从 Reset 方法中提取"提升"并将其添加到 Update 方法中,如下所示:
bool isReset = true;
public void Update(){
if(isReset && Input.GetKeyDown(KeyCode.Space){
if (startPosition == "Right"){
rbBall.velocity = Vector2.right * speed;
}else{
rbBall.velocity = -Vector2.right * speed;
}
isReset = false;
}
}
public void Reset (string startPosition)
{
transform.position = defaultPos;
isReset = true;
}
void Start(){
rbBall = GetComponent<Rigidbody2D>();
}
据我所知,这应该做你想做的事。
您的代码不起作用的原因是线程在等待单击空格键时不会暂停,它会检查一次,然后继续执行您要求它执行的其他操作。