unity3d游戏开发之发射子弹的源代码
今天讲了发射子弹并让子弹把墙打坏,并让打出去的子弹两秒后消失

 

详细代码如下:

1. using UnityEngine;

2. using System.Collections;

3. 

4. public class Fire : MonoBehaviour {

5. 

6.         float speed = 5.0f;

7.         

8.         public GameObject newObject;

9.         

10.         

11.         float firetima = 0.2f;

12.         float nexttime = 0.0f;

13.         

14.         

15.         void Update()

16.         {

17.                 float a = -25 * Time.deltaTime;

18.                 float x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;

19.                 float z = Input.GetAxis("Vertical") * Time.deltaTime * speed;

20.                 transform.Translate(x, 0, z);

21.                 if (Input.GetKey(KeyCode.Z))

22.                 {

23.                         transform.Rotate(Vector3.up * a, Space.Self);

24.                 }

25.                 if (Input.GetKey(KeyCode.X))

26.                 {

27.                         transform.Rotate(Vector3.down * a, Space.Self);

28.                 }

29.                 if (Input.GetButton("Fire1") && nexttime < Time.time)

30.                 {

31.                         nexttime = firetima + Time.time;

32.                         GameObject go = Instantiate(newObject, transform.position, transform.rotation) as GameObject;

33.                         go.rigidbody.AddForce(0, 0, 1231);

34.                         Destroy(go,2.0f);

35.                 }

36.                 

37.         }

38. 

39. }

 

接下来,我们要做一个太空大战的小游戏

具体实现效果是:

 

1、我方点击鼠标左键或按空格键发射子弹,我方子弹连续发射

 

2、敌方飞机和子弹自动运行,子弹每隔0.5秒向我方发射一颗

 

3、我方飞机移动时,敌方子弹跟随我方飞机移动

 

 

目前实现第一步代码部分

 

代码如下:

1. using UnityEngine;

2. using System.Collections;

3. 

4. public class Player : MonoBehaviour {

5.         float speed = -50.0f;

6.         

7.         public GameObject Myplayer;

8.         

9.         

10. 

11.         

12.         

13.         void Update()

14.         {

15.                 float a =  Time.deltaTime;

16.                 float x = Input.GetAxis("Horizontal") * Time.deltaTime * -speed;

17.                 float z = Input.GetAxis("Vertical") * Time.deltaTime * -speed;

18.                 transform.Translate(x, 0, z);

19.         

20.                 if (Input.GetButton("Fire1") )

21.                 {

22.                         //nexttime = firetima + Time.time;

23.                         GameObject go = Instantiate(Myplayer, transform.position, transform.rotation) as GameObject;

24.                         go.rigidbody.AddForce(0, 0, 1231);

25.                         Destroy(go,2.0f);

26.                 }

27.                 

28.         }

29. 

30. }

 

把脚本放到Player身上,(记得给子弹天加刚体),把预设体拖到