Unity学习笔记 之 发射小球碰撞物体的代码记录

绑定在摄像机上的脚本

using UnityEngine;
using System.Collections;

public class abc : MonoBehaviour {

	//设置移动速度
	public int speed = 5;

	//设置将被初始化载入的对象
	public Transform newobject = null;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		//通过左右方向键,或A、D字母键控制水平方向。实现往左、往右移动
		float x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
		//通过上下方向键,或W、S字母键控制垂直方向,实现往前、往后移动
		float z = Input.GetAxis("Vertical") * Time.deltaTime * speed;
		//移动 绑定物的 x、z 轴,即移动 摄像机的 x、z 轴。

transform.Translate(x,0,z); //推断是否按下鼠标的左键 if (Input.GetButtonDown("Fire1")) { //实例化命令:Instantiate(要生成的物体, 生成的位置, 生成物体的旋转角度) Transform n = (Transform)Instantiate(newobject, transform.position, transform.rotation); //转换方向 Vector3 fwd = transform.TransformDirection(Vector3.forward); //给物体加入力度 //Unity5之前的写法:n.rigidbody.AddForce(fwd * 2800); n.GetComponent<Rigidbody>().AddForce(fwd * 2800); } //推断是否按下字母button Q if (Input.GetKey(KeyCode.Q)) { //改变 绑定物的 y 轴,即改变 摄像机的 y 轴。 transform.Rotate(0,-25*Time.deltaTime,0,Space.Self); } //推断是否按下字母button E if (Input.GetKey(KeyCode.E)) { transform.Rotate(0,25*Time.deltaTime,0,Space.Self); } //推断是否按下字母button Z if (Input.GetKey(KeyCode.Z)) { //旋转 绑定物的 y 轴,即旋转 摄像机的 y 轴。 transform.Rotate(-25*Time.deltaTime,0,0,Space.Self); } //推断是否按下字母button X if (Input.GetKey(KeyCode.X)) { //旋转 绑定物的 y 轴,即旋转 摄像机的 y 轴。 transform.Rotate(25*Time.deltaTime,0,0,Space.Self); } //推断是否按下字母button F if (Input.GetKey(KeyCode.F)) { //移动 绑定物的 y 轴。即移动 摄像机的 y 轴。 transform.Translate(0,-5*Time.deltaTime,0); } //推断是否按下字母button C if (Input.GetKey(KeyCode.C)) { //移动 绑定物的 y 轴,即移动 摄像机的 y 轴。

transform.Translate(0,5*Time.deltaTime,0); } } }



绑定在发射的小球上的脚本

using UnityEngine;
using System.Collections;

public class xiaomie : MonoBehaviour {

	// Use this for initialization
	void Start () {
		//销毁物体,gameObject。目測应该是指物体自身。即达到自我销毁的需求.
		Destroy(gameObject, 3.0f);
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}


原文地址:https://www.cnblogs.com/claireyuancy/p/7047145.html