您的位置:首页 > 移动开发 > Unity3D

unity3d添加武器功能

2015-12-06 10:50 399 查看
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()函数,所以用GetKeyDown

Shoot();

}

}

void Shoot(){

GameObject newShell = Instantiate (shell, shootPoint.position, shootPoint.rotation) as GameObject;//用Instantiate函数克隆一个Object,并将Object转化为GameObject,存于newShell
Rigidbody r = newShell.GetComponent<Rigidbody> ();//r定义为newShell的刚体
r.velocity = shootPoint.forward * shootPower;//定义r的速度的方向及大小,速度方向为shootPoint.forward,大小为shootPower

}

}


注:

1.Instantiate函数的定义为:public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);

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

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

2.r.velocity的方向不可以直接使用(0,0,1),因为此z轴的向量是相对于世界坐标而言的,而forward是针对对象自身而言的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d