【发布时间】:2023-03-24 16:50:01
【问题描述】:
我目前在制作乒乓球游戏时遇到了问题。通常情况下,您会期望乒乓球的轨迹在每次调用 Reset() 后随机变化,但不知何故,它会停留在先前的轨迹中,并将沿着该路径继续。
using System.Collections.Generic;
using System.Collections;
using System;
using UnityEngine;
public class Ball : MonoBehaviour
{
Rigidbody2D rb;
float rand;
Vector3 ballinitialpos;
Vector3 lastpos;
Vector3 lastVect;
Vector3 newVect;
Vector2 directionVector;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
ballinitialpos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
Nudge();
}
void Nudge()
{
rand = UnityEngine.Random.Range(0, 2);
if (rand <= 1)
{
directionVector = new Vector3(-20f,10f,0f);
}
else
{
directionVector = new Vector3(20f,10f,0f);
}
rb.velocity = directionVector;
}
// Update is called once per frame
void Update()
{
lastVect = rb.velocity;
}
void Reset()
{
transform.position = ballinitialpos;
Nudge();
}
void ReflectVector(Vector3 vect, Collision2D collision) {
ContactPoint2D cp = collision.contacts[0];
newVect = Vector3.Reflect(vect.normalized,cp.normal);
rb.velocity = newVect * 20f;
}
void OnCollisionEnter2D(Collision2D col)
{
lastpos = transform.position;
ReflectVector (lastVect,col);
if (col.gameObject.CompareTag("hitboxP1") || col.gameObject.CompareTag("hitboxP2"))
{
Reset();
}
}
解释东西并不是我的强项。因此,如果我的问题令人困惑,请务必告诉我,我将根据您认为令人困惑的内容,尽我所能重新格式化问题。提前谢谢你。
【问题讨论】:
标签: c# unity3d game-development