小球跳动
1.给小球添加刚体组件
2.给小球的碰撞体添加物理材质(同时地面的碰撞体也要添加物理材质)
随时间增加,小球颜色变化
float t=0;
void Update () {
t += Time.deltaTime;
if (t > 0 && t <= 2) {
GetComponent<Renderer> ().material.color = Color.blue;
} else if (t > 2 && t <= 5) {
GetComponent<Renderer> ().material.color = Color.red;
} else {
t=0;
}
}
组件间的通信
1.找到游戏物体
GameObject myLight=GameObject.FindWithTag(“LxLight”);
或
GameObject myLight=GameObject.Find(“LxLight”);
2.找到组件
Light l=myLight.GetComponent ();
3.找到脚本
ChangeColor c=cube.GetComponent ();
4.调用其他脚本的方法
c.SendMessage(“OnMouseDown”);
5.实例:通过案件调节灯光亮度,及小球的方法
GameObject myLight;
Light l;
GameObject cube;
ChangeColor c;
// Use this for initialization
void Start () {
myLight=GameObject.FindWithTag("LxLight");
l = myLight.GetComponent<Light> ();
cube=GameObject.Find("Cube");
c = cube.GetComponent<ChangeColor> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.L)) {
l.intensity-=0.1f;
}
if (Input.GetKey (KeyCode.U)) {
l.intensity+=0.1f;
}
if (Input.GetKey (KeyCode.S)) {
c.SendMessage("OnMouseDown");
}
}
第一人称角色控制器
准备工作
1.新建一个胶囊体
2.在胶囊体的子节点添加一个相机
3.添加移动脚本Player
4.添加Character Controller
胶囊体脚本Player
public class Player : MonoBehaviour {
public float speed=6f;
public float jumpspeed=8f;
float gravity=20f;
Vector3 moveDirection=Vector3.zero;
bool grouned=false;
CharacterController controller;
CollisionFlags flags;
// Use this for initialization
void Start () {
controller = GetComponent<CharacterController> ();
}
void FixedUpdate () {
if (grouned) {
moveDirection=new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
moveDirection=transform.TransformDirection(moveDirection);
moveDirection*=speed;
if(Input.GetButton("Jump")){
moveDirection.y=jumpspeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
//flage=CollisionFlags.CollidedBelow;底部碰撞
//flage=CollisionFlags.None;未碰撞
//flage=CollisionFlags.CollidedSides;底部碰撞
//flage=CollisionFlags.Above;
flags = controller.Move (moveDirection * Time.deltaTime);
grouned = ((flags & CollisionFlags.CollidedBelow) != 0);
}
}