Unity在角度发射刚体

时间:2018-05-17 01:23:11

标签: c# unity3d game-physics rigid-bodies

我希望以30˚的角度和30 m / s的速度发射我的箭头 GameObject。在脚本中,我为此箭头添加了一个刚体。但是,我也试图在 3D场景中向玩家(远离敌人)方向发射箭头。我无法弄清楚如何插入这些变量来获取“arrowRigidbody.velocity”的Vector3

//THE VARIABLES REFERENCED ABOVE APPEAR LIKE SO:
Rigidbody arrowRigidbody;
Transform playerTransform;
Transform enemyTransform;
float angle = 30f;
float velocity = 30f;

//How do I use these variables in order to shoot the projectile at a speed
//of 30 m/s and an angle of 30˚ in the direction of the player in 3D scene
arrowRigidbody.velocity = /*????*/;

感谢您的时间和耐心:)

2 个答案:

答案 0 :(得分:0)

使用某些几何,知道向量的幅度(m)为1,y分量为m / 2,x分量为m *(3 ^ .5)/ 2。这将使你的最终价值:

arrowRigidbody.velocity = new Vector2(Mathf.Pow(3, .5f)/2, 1/2) * velocity;

对于变化的角度,你知道x分量将是m * cos(角度),y分量将是m * sin(角度),留下你:

float velx = velocity * Mathf.Cos(angle * Mathf.Deg2Rad);
float vely = velocity * Mathf.Sin(angle * Mathf.Deg2Rad);
arrowRigidbody.velocity = new Vector2(velx, vely);

答案 1 :(得分:0)

假设你只拍'前锋',你可以使用简化版:

    var targetDirn = transform.forward;
    var elevationAxis = transform.right;

    var releaseAngle = 30f;
    var releaseSpeed = 30f;

    var releaseVector = Quaternion.AngleAxis(releaseAngle, elevationAxis) * targetDirn;
    arrowRigidbody.velocity = releaseVector * releaseSpeed;

如果您需要拍摄'离轴',可以替换前两行:

    var targetDirn = (target.transform.position - transform.position).normalized;
    var elevationAxis = Vector3.Cross(targetDirn, Vector3.up);