问题描述
我正在制作 3D 突破性游戏,这是我第一次制作游戏并使用 Unity,所以我有点无能为力。在球离开屏幕并进入“死区”之前,我已经到了我的游戏运行良好的地步。 有人可以建议如何将桨和球一起重生并继续游戏吗? 我在下面包含了我的球和桨脚本,我也有一个砖块脚本,但不确定是否相关。我还制作了一个球和桨的预制件,但不知道如何处理它。 感谢任何可以提供帮助的人:)
我的球代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript : MonoBehavIoUr
{
public Rigidbody rbody;
public float MinVertMovement = 0.1f;
public float MinSpeed = 10f;
public float MaxSpeed = 10f;
private bool hasBeenLaunched = false;
void Start()
{
}
private float minVeLocity = 10f;
private Vector3 lastFrameVeLocity;
void FixedUpdate()
{
if (hasBeenLaunched == false)
{
if (Input.GetKey(KeyCode.Space))
{
Launch();
}
}
if (hasBeenLaunched)
{
Vector3 direction = rbody.veLocity;
direction = direction.normalized;
float speed = direction.magnitude;
if (direction.y>-MinVertMovement && direction.y <MinVertMovement)
{
direction.y = direction.y < 0 ? -MinVertMovement : MinVertMovement;
direction.x = direction.x < 0 ? -1 + MinVertMovement : 1 - MinVertMovement;
rbody.veLocity = direction * MinSpeed;
}
if (speed<MinSpeed || speed>MaxSpeed)
{
speed = Mathf.Clamp(speed,MinSpeed,MaxSpeed);
rbody.veLocity = direction*speed;
}
}
lastFrameVeLocity = rbody.veLocity;
}
void OnCollisionEnter(Collision collision)
{
Bounce(collision.contacts[0].normal);
}
private void Bounce(Vector3 collisionnormal)
{
var speed = lastFrameVeLocity.magnitude;
var direction = Vector3.Reflect(lastFrameVeLocity.normalized,collisionnormal);
Debug.Log("Out Direction: " + direction);
rbody.veLocity = direction * Mathf.Max(speed,minVeLocity);
}
public void Launch()
{
rbody = GetComponent<Rigidbody>();
Vector3 randomDirection = new Vector3(-5f,10f,0);
randomDirection = randomDirection.normalized * MinSpeed;
rbody.veLocity = randomDirection;
transform.parent = null;
hasBeenLaunched = true;
}
}
我的桨的代码
public class PaddleScript : MonoBehavIoUr
{
private float moveSpeed = 15f;
void Start()
{
}
void Update()
{
if (Input.GetKey(KeyCode.RightArrow) && transform.position.x<9.5)
transform.Translate(moveSpeed *Input.GetAxis("Horizontal")*Time.deltaTime,0f,0f);
if (Input.GetKey(KeyCode.LeftArrow) && transform.position.x>-7.5)
transform.Translate(moveSpeed *Input.GetAxis("Horizontal")*Time.deltaTime,0f);
}
}
解决方法
检查球是否离开屏幕的最简单方法是立即将 trigger 放置在相机周边之外,并为球添加 OnTriggerEnter2D 方法。
/* Inside the ball script */
private void OnTriggerEnter() { // Use the 2D version if you're using 2D colliders
/* Respawning stuff */
}
由于您可能希望在该方法触发时发生一系列不同的事情,因此您可能希望使用 Unity Event,这不是性能之王,但对于突破之类的游戏来说可能无关紧要.
using UnityEngine.Events;
public class BallScript : MonoBehaviour
{
public UnityEvent onBallOut;
/* ... */
private void OnTriggerEnter() {
onBallOut.Invoke();
}
}
然后您可能需要一个 Respawn() 方法(不是 Reset(),因为这是一个默认的 MonoBehaviour 调用)将球放回其原始位置,您可以在场景加载后立即将其存储在一个字段中:>
private Vector3 defaultPosition;
private void Start() {
defaultPosition = transform.position;
}
PS:如果您没有在 paddle 脚本中使用 Start() 方法,请将其删除,因为即使为空,Unity 也会调用它。