我正在制作第一人称射手剧本。为了让子弹直接在十字准线上行进,我计算出光线射击并向那个方向射击子弹。问题是如果范围内没有任何东西,它根本不会射击,这不是枪的工作方式。我现在的剧本现在检查是否有击中,如果没有击中,它默认是直接射出枪。像这样:
void Update () {
if(Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(crossHair.transform.position);
GameObject bullet = Instantiate(bullet_prefab, bullet_spawn.transform.position, bullet_spawn.transform.rotation) as GameObject;
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
if (Physics.Raycast(ray, out rayHit, 100000.0f))
{
Debug.DrawLine(bullet_spawn.transform.position, rayHit.point, Color.red);
bulletRigidbody.AddForce((rayHit.point - bullet_spawn.transform.position).normalized * bulletImpulse, ForceMode.Impulse);
}
else
{
bulletRigidbody.AddForce(bullet_spawn.transform.position * bulletImpulse, ForceMode.Impulse);
}
EmitShotParticles();
}
}
问题在于它似乎不公平。玩家可以将十字准线直接放在目标旁边并仍然击中它们。我需要一种方法来持续射击直接射到枪上的十字准线,而不是两次单独的子弹路径计算。
答案 0 :(得分:0)
为什么你甚至需要Raycast(...)
??
if(Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(crossHair.transform.position);
GameObject bullet = Instantiate(bullet_prefab, bullet_spawn.transform.position, bullet_spawn.transform.rotation) as GameObject;
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
Vector3 direction = (ray.GetPoint(100000.0f) - bullet.transform.position).normalized;
bulletRigidbody.AddForce(direction * bulletImpulse, ForceMode.Impulse);
EmitShotParticles();
}
答案 1 :(得分:0)
您需要在没有射线投射的情况下发射子弹,并在命中时或射线投射成功时发射粒子。
答案 2 :(得分:-1)
有一个很好的第一人称射击教程here。
其中包含拍摄代码(如下)。你所需要的只是一个火箭(或子弹)预制件和附在(例如)你的枪上的射击脚本。
public GameObject rocketPrefab;
void Update () {
// left mouse clicked?
if (Input.GetMouseButtonDown(0)) {
GameObject g = (GameObject)Instantiate(rocketPrefab, transform.position, transform.parent.rotation);
// make the rocket fly forward by simply calling the rigidbody's
// AddForce method
// (requires the rocket to have a rigidbody attached to it)
float force = g.GetComponent<Rocket>().speed;
g.rigidbody.AddForce(g.transform.forward * force);
}
}