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;
}
1 回答
您使用相机的
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
.并为此工作的代码: