簡體   English   中英

Unity3D 幫助 - 沿玩家旋轉方向射擊物體

[英]Unity3D Help - Shooting object in direction of player rotation

我正在制作第三人稱體育游戲,我希望從玩家直接向前射球。

我有一個用於拍攝球的工作腳本,但是它連接到主攝像機,因此只能朝攝像機面向的方向拍攝。

我想更改此代碼以將其附加到播放器而不是相機。

PS:我對 C# 還是很陌生,我認為問題出在“camera.main.transform”部分,但我不知道將其更改為播放器的代碼。

我的代碼在下面;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootScript : MonoBehaviour
{
    public GameObject bulletPrefab;
    public float shootSpeed = 300;

    Transform cameraTransform;

    void Start()
    {
        cameraTransform = camera.main.transform;
    }

    void Update()
    {  
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            shootBullet();
        }
    }
    void shootBullet()
    {       
        //Get the Rigidbody that is attached to that instantiated bullet
        Rigidbody projectile = GetComponent<Rigidbody>();

        //Shoot the Bullet
        projectile.velocity = cameraTransform.forward * shootSpeed;
    }
}

首先:您目前在該對象本身上執行GetComponent<Rigidbody> .. 這是沒有意義的,因為它會發射“你自己”而不是子彈。 您必須在此處Instantiate子彈並施加力/速度。 你有點錯過了實例化。

然后只需將此腳本附加到您的播放器對象並使用transform.forward transform返回此腳本附加到的 GameObject 的Transform組件。

public class ShootScript : MonoBehaviour
{
    // Hint: By making the prefab field Rigidbody you later can skip GetComponent
    public Rigidbody bulletPrefab;
    public float shootSpeed = 300;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            shootBullet();
        }
    }

    void shootBullet()
    {
        // Instantiate a new bullet at the players position and rotation
        // later you might want to add an offset here or 
        // use a dedicated spawn transform under the player
        var projectile = Instantiate (bulletPrefab, transform.position, transform.rotation);

        //Shoot the Bullet in the forward direction of the player
        projectile.velocity = transform.forward * shootSpeed;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM