unity3d添加武器功能

来源:互联网 发布:js获取某个div的高度 编辑:程序博客网 时间:2024/04/29 16:10
using UnityEngine;using System.Collections;public class TankWeapons : MonoBehaviour {public GameObject shell;public float shootPower;//确定子弹的发射力public Transform shootPoint;//确定子弹的发射点。新建一个tank的空子物体,用来记录子弹的发射位置void Update () {if (Input.GetKeyDown (KeyCode.Space)) {//当按下空格时,调用Shoot()函数,所以用GetKeyDownShoot();}}void Shoot(){GameObject newShell = Instantiate (shell, shootPoint.position, shootPoint.rotation) as GameObject;//用Instantiate函数克隆一个Object,并将Object转化为GameObject,存于newShellRigidbody r = newShell.GetComponent<Rigidbody> ();//r定义为newShell的刚体r.velocity = shootPoint.forward * shootPower;//定义r的速度的方向及大小,速度方向为shootPoint.forward,大小为shootPower}}


注:

1.Instantiate函数的定义为:public static Object Instantiate(Object originalVector3 positionQuaternion rotation);

作用为复制一个Object并返回。(由于此代码中要的是GameObject,所以要进行一次类型转换,C#中直接用as转换)

original为要复制的对象,position为返回对象的位置,rotation为返回对象的旋转角。

2.r.velocity的方向不可以直接使用(0,0,1),因为此z轴的向量是相对于世界坐标而言的,而forward是针对对象自身而言的。

0 0
原创粉丝点击