c# - 为什么玩家移动错误 - Unity 3D C#
问题描述
我的场景中有一个球,我想让它以恒定的速度向前移动,所以我为这个球编写了以下代码:
public float speed = 100f;
void FixedUpdate () {
//rb.AddRelativeForce(Vector3.forward * speed * Time.deltaTime);
transform.position += Vector3.forward * Time.deltaTime * speed;
//rb.AddForce(0, 0, speed *Time.deltaTime);
//rb.velocity = transform.forward * speed;
}
注意:我已经尝试了您在评论中看到的所有代码 (//...)
问题是球有时会自己破坏,有时速度会降低,或者当球与其他物体碰撞时,它会以一种奇怪的动作前后移动!
这是整个代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(AudioSource))]
public class PlayerMovement : MonoBehaviour {
public AudioSource audioSource1;
public AudioSource audioSource2;
public Transform BallDestroyEffect;
public ParticleSystem BallCollectEffect;
public ParticleSystem SpeedEffect;
public ParticleSystem FireWorksEffect;
public GameObject FloatingTextPrefab;
public GameObject ContinueButton;
public Rigidbody rb;
public float speed = 100f;
private int count;
public Text countText;
public Text winText;
bool gameStart;
private void Start()
{
BallCollectEffect.Stop();
FireWorksEffect.Stop();
ContinueButton.SetActive(false);
rb = GetComponent<Rigidbody>();
count = 0;
setcountText();
winText.text = "";
audioSource1 = GetComponent<AudioSource>();
audioSource2 = GetComponent<AudioSource>();
}
void FixedUpdate () {
//rb.AddRelativeForce(Vector3.forward * speed * Time.deltaTime);
//transform.position += Vector3.forward * Time.deltaTime * speed;
//rb.AddForce(0, 0, speed *Time.deltaTime);
//rb.velocity = transform.forward * speed;
rb.MovePosition(transform.position + transform.forward * speed);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag ("Enemy"))
{
audioSource2.Play();
SpeedEffect.Stop();
rb.gameObject.SetActive(false);
Instantiate(BallDestroyEffect, transform.position, transform.rotation);
FindObjectOfType<GameManager>().EndGame();
}
if (collision.gameObject.CompareTag("End"))
{
ContinueButton.SetActive(true);
winText.text = "Level Completed!";
SpeedEffect.Stop();
FireWorksEffect.Play();
}
if(collision.gameObject.CompareTag("Glass"))
{
audioSource1.Play();
count = count + 3;
setcountText();
BallCollectEffect.Play();
if (FloatingTextPrefab)
{
ShowFloatingText();
}
}
}
void ShowFloatingText()
{
Instantiate(FloatingTextPrefab, transform.position, Quaternion.identity, transform);
}
void setcountText () {
countText.text = count.ToString();
}
}
你对此有什么建议吗?
解决方案
Rigidbody.MovePosition()
如果您想在每个 FixedUpdate中连续移动刚体,则应使用此选项。
如果您想将刚体从一个位置传送到另一个位置,而不渲染中间位置,
Rigidbody.position
请改为设置。
注意这两个句子的区别。
推荐阅读
- google-sheets - 谷歌表格拖动公式的一部分,同时保持其余部分不变
- sweetalert2 - Sweealert2:未知参数图标
- ffmpeg - 使用 ffmpeg 将视频从 .264 转换为 .265 (HEVC)
- python - 如何在 TensorFlow 中获取日志概率?
- javascript - 如何在 jQuery datepicker 中仅验证一年的日期
- wordpress - 为什么网站的等待时间太长
- image - 是否能够在不损失 WPF 中图像质量的情况下更改图像大小?
- php - 在 Laravel 中添加和更新语言文件数组
- javascript - 用于浏览器和 nodeJS 的通用 JS 以及单元测试
- c# - 如何统一截图,可以在IOS和Android中使用