首页 文章

如何移动3D射弹Unity

提问于
浏览
1

我试图了解在Unity中创建3D射弹的过程 . 在为数不多的关于制作普通激光弹丸的网上帖子中,关于这个过程的解释很少 . 有人可以帮助我理解像是如何接近射击射弹的逐步方法 .

问题我想了解:

  • 如何在射击游戏对象面向的方向上移动射弹 . 使用position.Translate()方法强制我选择一个特定的方向来移动对象 .

1 回答

  • 2

    如何将射弹向射击游戏对象所面向的方向移动

    您使用相机的 Transform.forward 使射弹行进到玩家所面对的位置 .

    射击射弹的过程如下:

    1 . 实例化/创建子弹

    2 . 设置子弹在玩家面前的位置

    3 . 获取附加到该实例化项目符号的 Rigidbody

    4 . 如果这只是带有角色控制器的相机并且没有可见的枪,

    使用 Camera.main.Transform.Position.forward shootSpeed 变量拍摄子弹 .

    如果您想要拍摄可见的枪或物体,

    创建另一个GameObject(ShootingTipPoint),它将用作子弹应该射击的位置并将其放置在你想要射击的枪或物体的位置,然后你使用GameObject的 ShootingTipPoint.Transform.Position.forward 射击子弹而不是 Camara.Main.Transform.Position.forward .

    并为此工作的代码:

    public GameObject bulletPrefab;
    public float shootSpeed = 300;
    
    Transform cameraTransform;
    
    void Start()
    {
        cameraTransform = Camera.main.transform;
    }
    
    void Update()
    {
    
        if (Input.GetKeyDown(KeyCode.Space))
        {
            shootBullet();
        }
    }
    void shootBullet()
    {
        GameObject tempObj;
        //Instantiate/Create Bullet
    
        tempObj = Instantiate(bulletPrefab) as GameObject;
    
        //Set position  of the bullet in front of the player
        tempObj.transform.position = transform.position + cameraTransform.forward;
    
        //Get the Rigidbody that is attached to that instantiated bullet
        Rigidbody projectile = GetComponent<Rigidbody>();
    
        //Shoot the Bullet 
        projectile.velocity = cameraTransform.forward * shootSpeed;
    }
    

相关问题