检测光线投射来自哪个角度

时间:2021-01-31 09:31:28

标签: c# unity3d quaternions

问题是这样的:我想改变一个物体下落的方向,以适应光线投射(在这种情况下是子弹)的来源。到目前为止,我的代码是这样的:

public class Target: MonoBehaviour
{
    public float health = 20f;
    public Rigidbody rb;
    bool dead = false;
    
    public void TakeDamage(float damage)
    {
        health -= damage;
        if (health <= 0f)
        {
            Die();
        }
    }

    void Die()
    {
        if (dead == false)
        {
            dead = true;
            rb.AddForce(20, 0, 0);
        }

    }
}

需要旋转 rb.AddForce,以适应光线投射的来源。

更新

if (dead == false)
        {
            dead = true;
            rb.AddForce(rb.position - shooter.position);
        }

这解决了问题,我还添加了射手变换

1 个答案:

答案 0 :(得分:0)

假设我理解你的问题(SO 的规则还不允许我要求澄清,我只能发布硬性答案),你可以修改你的 TakeDamage() 函数,以便它接收光线。然后,从您实际发射 Ray 的任何地方(我猜是您的枪或玩家脚本),只需将其传递给 TakeDamage()。

但要清楚的是,这会在射线方向上增加力,因此您的目标将被推向子弹前进的方向。您可能正在寻找更复杂的行为。如果您希望目标根据子弹击中的位置做出真实的反应,请查看 AddForceAtPostion,它可以让您既推动目标,又真实地旋转它。

import hoistNonReactStatics from 'hoist-non-react-statics';

type HOC<InnerProps, OuterProps = InnerProps> = (
  Component: React.ComponentType<InnerProps>,
) => React.ComponentType<OuterProps>;

const hoistStatics = <InnerProps, OuterProps>(
  higherOrderComponent: HOC<InnerProps, OuterProps>,
): HOC<InnerProps, OuterProps> => (
  BaseComponent: React.ComponentType<InnerProps>,
) => {
  const NewComponent = higherOrderComponent(BaseComponent);
  hoistNonReactStatics(NewComponent, BaseComponent);
  return NewComponent;
};

export default hoistStatics;