如何让子弹直接向前发射,而忽略玩家的物理特性(滚动)?



我的代码的问题在于子弹基本上会从玩家对象中溢出,但我无法让它们直接向前射击以击中障碍物。 相反,当玩家滚动每个方向时,子弹会从相同的设定矢量出来,这不是我想要的。我希望子弹只沿着 x 轴射击,而相反,它们会根据玩家的滚动方式从四面八方射出。

我尝试过改变子弹旋转和力,以防子弹力改变玩家的方向和动量。那失败了,所以我移除了球员前进的力量进行测试,仍然没有进展。

using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float backwardForce = -60f;
public float forwardForce = 100f;
public float sidewaysForce = 1f;
// Start is called before the first frame update
void Start()
{
rb.AddForce(0, 100, 200);
}
// Update is called once per frame
void FixedUpdate()
{
//Movement force
rb.AddForce(0, 0, 50.0f * Time.deltaTime);
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (Input.GetKey("w"))
{
rb.AddForce(forwardForce * Time.deltaTime, 0, 0, ForceMode.Force);
}
else if (Input.GetKey("s"))
{
rb.AddForce(backwardForce * Time.deltaTime, 0, 0, ForceMode.Force);
}

/*switch (Input.GetKeyDown())
{
// case Input.GetKeyDown("a"):

//a: rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
}
}
}
public class BulletShoot : MonoBehaviour
{
//Reference to bullet emitter
public GameObject Bullet_Emitter;
//Reference to bullet prefab
public GameObject Bullet;
//Forward force of bullet
public float Bullet_Force;// = 10.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//When "Space" key is pressed..
if (Input.GetKey("space")){
//Temp variable that will hold reference to bullet
GameObject tempBulletHandler;
//Temp then instantiates bullet to game using emitter position and angle
tempBulletHandler = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation);
//Corrects angle that bullets appear
tempBulletHandler.transform.Rotate(Vector3.left * 180);
//RigidBody instantiated to control bullet physics using bullet handler
Rigidbody tempRigidBody = tempBulletHandler.GetComponent<Rigidbody>();
//Add force to the rigidbody to simulate firing the bullet forward using set bullet force
tempRigidBody.AddForce(Vector3.forward * Bullet_Force);
//Free up space from bullets fired (after 4 sec)
Destroy(tempBulletHandler, 4.0f);
}
}
}

预期:玩家不断向前移动,同时具有沿线性方向射击障碍物的能力。

实际:玩家移动正确,但子弹无法控制地发射,就像米饭从袋子里掉出来一样,袋子里有一个洞,不断向各个方向旋转。

这是一个常见的早期问题,当你实例化项目符号、箭头,甚至是来自某物的粒子时,如果你实例化(myprefab,transform),你分配的任何变换现在都是对象的父级。所以,如果那个实例是一个供玩家携带的盒子,那很好,因为随着父母/玩家的移动,盒子也会移动,太好了。 不需要编码。

想象一下太空入侵者,如果你向左开火,然后想向最右边开火,你期望的是你发射的导弹保持上升,在那个纵队中令人讨厌,目前会发生什么是你的导弹当你向右移动时,也会向右移动。您需要取消对导弹的父级,以便它现在可以愉快地移动,并可以自由地朝着您设置的方向移动。

简而言之,您将设置 missle.transform.SetParent(newParent);其中 newparent 甚至可以为 null,这会将其置于层次结构的顶层。

最新更新