我正在制作一款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, 0f);
}
}
要检查球是否离开屏幕,最简单的方法是将触发器立即放置在相机外围,并将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((,因为这是默认的MonoBehavior调用(,将球放回其原始位置,一旦场景加载,您就可以将其存储在字段中:
private Vector3 defaultPosition;
private void Start() {
defaultPosition = transform.position;
}
PS:如果你没有在你的桨板脚本中使用Start((方法,那么就删除它,因为即使它为空,Unity也会调用它。