Unity. Куб отражается от обычной стены, но застревает в стене из кубов меньше его в 2 раза
Молю о помощи. Имеется куб scale(0.5, 0.5, 0.5) и 1 скрипт для него. Куб отражается от обычной стены но застревает и бьется из стороны в сторону при случайном ударе об стену состоящую из таких же кубов но поменьше scale(0.25, 0.6, 0.25).
Уже пробовал использовать для перемещения transform.position += direction * speed * Time.deltaTime;
вместо GetComponent<Rigidbody>().MovePosition(transform.position + direction * speed * Time.fixedDeltaTime);
, перекомбенировал все значения свойства Collision Detection
компонента RigidBody
пробовал GetComponent<Rigidbody>().AddForce();
даже менял значения Time
в настройках проекта.
using UnityEngine;
public class cubescript : MonoBehaviour
{
public Rigidbody rb;
public float speed = 0f;
Vector3 direction = Vector3.zero;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
speed = 1.5f;
rb = GetComponent<Rigidbody>();
direction = new Vector3(-1, 0, 1);
}
// Update is called once per frame
void Update()
{
GetComponent<Rigidbody>().MovePosition(transform.position + direction * speed * Time.fixedDeltaTime);
}
private void OnCollisionEnter(Collision collision)
{
direction = Vector3.Reflect(direction, collision.contacts[0].normal);
direction.y = 0;
}
}
Ответы (1 шт):
Похоже, что он регистрирует OnCollisionEnter
от двух объектов одновременно. Можно проверять что 2 коллизии не произошли в один кадр:
using UnityEngine;
public class cubescript : MonoBehaviour
{
public Rigidbody rb;
public float speed = 0f;
Vector3 direction = Vector3.zero;
private bool hasCollidedThisFrame = false;
void Start()
{
speed = 1.5f;
rb = GetComponent<Rigidbody>();
direction = new Vector3(-1, 0, 1);
}
void Update()
{
rb.MovePosition(transform.position + direction * speed * Time.fixedDeltaTime);
}
private void OnCollisionEnter(Collision collision)
{
if (!hasCollidedThisFrame)
{
direction = Vector3.Reflect(direction, collision.contacts[0].normal);
direction.y = 0;
hasCollidedThisFrame = true;
}
}
private void LateUpdate()
{
hasCollidedThisFrame = false;
}
}