我正在做第三人称体育游戏,我希望直接从球员那里投篮。
我有一个用于拍摄球的有效脚本,但是它附着在主相机上,因此只能以相机面向的方向射击。
我想更改此代码以将其附加到播放器而不是相机。
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
子弹并在此处施加力/速度。您有点想念实例化。
然后只需将此脚本附加到播放器对象上,然后使用Instantiate
。 transform.forward
返回此脚本附加到的GameObject的transform.forward
组件。
transform