【问题标题】:Trying to get reversed movement on collision on Unity2试图在 Unity 中的碰撞时获得反向运动
【发布时间】:2021-05-13 18:37:52
【问题描述】:

所以我正在尝试制造一种射击机器,它可以发射子弹,子弹从撞击墙壁时的相同方式返回,而不加速且不改变角度(正好相反) 我加了力并尝试了很多方法,但没有任何效果,请帮助

这是我的代码(最后一个),尽管我将力标准化,但我仍然觉得它在加速

public Rigidbody2D rb;
private float bulletForce = 20f;

private bool collided;

Vector2 dir;
private void Awake()
{
    instance = this;
    rb = gameObject.GetComponent<Rigidbody2D>();
    dir = transform.up;

}

void Update()
{

    rb.AddForce(dir.normalized * bulletForce * Time.deltaTime, ForceMode2D.Impulse);
    
}

private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.CompareTag("Edge"))
    {
        dir = Vector2.Reflect(rb.position, other.contacts[0].normal);
        rb.velocity = dir.normalized * bulletForce;
        transform.up = dir.normalized;
    }
}

this is wanted results explanation

this is current results explanation

【问题讨论】:

  • 你为什么不希望它真实地反弹?游戏创意是什么,让我们更了解您想要什么。

标签: unity3d 2d collision


【解决方案1】:

如果你只是想完全反转方向而不是

rb.velocity = -rb.velocity;
transform.up = rb.velocity;

当然它正在加速,因为你不断增加力量

void Update()
{
    rb.AddForce(dir.normalized * bulletForce * Time.deltaTime, ForceMode2D.Impulse);   
} 

为什么不禁用此子弹的任何摩擦并设置初始速度一次

【讨论】:

    【解决方案2】:
    public class CollideReflector : MonoBehaviour
    {
        [SerializeField] Rigidbody2D rb;
        [SerializeField] Vector2 direction;
        [SerializeField] float bulletForce = 20f;
        [SerializeField]float smooth;
        private bool collided;
    
        // STARTER
        private void Awake()
        {
            instance = this;
            rb = gameObject.GetComponent<Rigidbody2D>();
            direction = transform.up;
    
        }
    
        void Update()
        {
    
            rb.AddForce(direction.normalized * bulletForce * Time.deltaTime, ForceMode2D.Impulse);
            
        }
    
        private void OnCollisionEnter2D(Collision2D other)
        {
            if (other.gameObject.CompareTag("Edge"))
            {
            var x = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z);           
            Quaternion target = -x;
            transform.rotation = Quaternion.Slerp(transform.rotation, x,  Time.deltaTime * smooth);      
            rb.AddForce(-direction.normalized * bulletForce * Time.deltaTime, ForceMode2D.Impulse);
            }
        }
    
    }
    

    【讨论】:

    • 你可以试试这个
    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多