如何将立方体从墙上弹起并朝其对角的方向移动

问题描述 投票:0回答:1

我一直在尝试沿随机方向自动移动立方体,并用彩色点标记角。我想要做的是与墙壁碰撞并将立方体从其角上弹向相反的点。我希望立方体在 x 和 y 平面上保持直线运动,并且行为类似于乒乓球。立方体可以旋转,因此可以在角上碰撞。

我尝试使用函数 LookAt 并朝该方向施加力。之后,我尝试使用从与墙壁碰撞的立方体的角落进行光线投射拍摄。该光线投射将向立方体对角的方向射出,并向碰撞点移动。我认为 MoveTowards 函数可以做到这一点。

这是我的弹跳代码

    
    public class CollideCheck : MonoBehaviour
    {
        private bool isCollided;
        private int direction;
        

        public bool IsCollided
        {
            get { return isCollided; }
        }

        public GameObject YellowMarker { get; private set; }



        void OnCollisionEnter(Collider other)
        {
            if (other.gameObject.tag == "RedMarker")
            {
                

                void RaycastTowardsThing(GameObject other)
                {
                    Vector3 raycastDir = other.transform.position - transform.position;

                    Physics.Raycast(transform.position, raycastDir);
                    

                }

                RaycastTowardsThing(YellowMarker);

            }
private void OnCollisionEnter(Collider other)
        {
            transform.position = Vector3.MoveTowards(transform.position, yellow.transform.position)
        }

Here's How the cube bounces

visual-studio unity-game-engine pong
1个回答
0
投票

我在开发“Brick Breaker”游戏时也在做类似的事情。

要计算并沿相反方向移动立方体,您需要首先计算方位,或者立方体来自的方向。这是通过计算两者之间的向量来完成的。

private void OnCollisionEnter(Collider other)
{
        Vector3 heading = other.transform.position - transform.position;
}

其次,需要反转向量并计算相反的方向。

private void OnCollisionEnter(Collider other)
{
        Vector3 heading = other.transform.position - transform.position;
        Vector3 direction = -heading / heading.magnitude;
}

最后,您将方向矢量作为速度添加到立方体的 RigidBody 中,并将其乘以某个速度;

private void OnCollisionEnter(Collider other)
{
        Vector3 heading = other.transform.position - transform.position;
        Vector3 direction = -heading / heading.magnitude;
        rb.velocity = direction * speed;
}

我不确定它的行为是否与您想要的完全相同,但我认为我提供了如何沿相反方向移动立方体的总体思路。

© www.soinside.com 2019 - 2024. All rights reserved.