我是靠谱客的博主 温婉小霸王,最近开发中收集的这篇文章主要介绍Unity子弹生成,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
public float LifeTime = 3.0f;
public int damage = 50;
public float beamVelocity = 100;
public void Go ()
{
GetComponent<Rigidbody>().AddForce(transform.forward * 10, ForceMode.VelocityChange);
}
void FixedUpdate()
{
GetComponent<Rigidbody>().AddForce(transform.forward * beamVelocity, ForceMode.Acceleration);
}
void Start()
{
Destroy(gameObject, LifeTime);
}
void Update()
{
//transform.position += transform.forward * Speed * Time.deltaTime;
}
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}

以上是Bullet脚本

下面是player的脚本

void Shoot(){
shootTimer -= Time.deltaTime;
if(Input.GetButtonUp("Fire1") && shootTimer <= 0){
shootTimer = 0.1f;
GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation) as GameObject;
bullet.GetComponent<Bullet>().Go();
//发出枪声
GetComponent<AudioSource>().PlayOneShot(shootSound);
//减少子弹
GUIManager.instance.SubBullet(1);
RaycastHit hitInfo;
//射线检测
bool hit = Physics.Raycast(
muzzlepoint.position,
cameraTransform.TransformDirection(Vector3.forward),
out hitInfo, 100, layerMask);
if(hit){
if(hitInfo.collider.gameObject.tag == "enemy"){
hitInfo.collider.gameObject.SendMessage ("OnDamage", 1);
}
Instantiate(fx, hitInfo.point, hitInfo.transform.rotation);
}
}
}

这里最重要的是 GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation) as GameObject;尤其是第四个参数bulletSpawnPoint.rotation。
如果改成Quaternion.identity,子弹永远只会朝着世界坐标的某个方向发射,无论第一视角怎么旋转都不行。

第二个重要的是出枪口的设置,有些时候会直接使用模型的枪管部分作为bulletprefab,这是不正确的,第一视角的枪往往是有点倾斜的,所以发出的所有子弹都会在出枪的瞬间先倾斜同样的角度,故子弹都会漂移。

解决的办法就是让镜头作为父物体,创建一个空的子物体作为出枪口bulletprefab,再把这个子物体移动放置在枪支模型的枪口上就可以了。

最后

以上就是温婉小霸王为你收集整理的Unity子弹生成的全部内容,希望文章能够帮你解决Unity子弹生成所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部