В моей сцене есть мяч, который я хочу перемещать вперед с постоянной скоростью, поэтому я сделал этот код для шара:
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;
}
NB: я перепробовал всекоды, которые вы видите в комментариях (//...)
Проблема в том, что иногда мяч сам разрушается, а иногда снижается скорость, или когда мяч сталкивается с другим объектом, он уходитвперед и назад в странном движении!
Вот весь код:
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();
}
}
У вас есть предложения по этому поводу?