直接上代碼:
[csharp]
using UnityEngine;
using System.Collections;
public class findFloor : MonoBehaviour {
private Vector3 floorPosition;
private RaycastHit hit;
private float rayLength = 300;
private float ySpeed=20;
private float gravity=2f;
private float jumpForce=1f;
public Transform character;
private uint jumpState=0; //0=grounded 1=jumping
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
DetectKeys();
FindFloorAndRotation();
MoveCharacter();
MoveCamera();
}
void DetectKeys(){
//jump:
if (Input.GetKeyDown("space") && jumpState==0) {
ySpeed-=jumpForce;
jumpState=1;
}
}
void FindFloorAndRotation(){
if (Physics.Raycast(character.position,-Vector3.up,out hit, rayLength)){
Debug.DrawRay(character.position, -Vector3.up * hit.distance);
floorPosition=hit.point;
}
}
void MoveCharacter(){
//add gravity:
ySpeed += gravity * Time.deltaTime;
//apply gravity:
character.position=new Vector3(floorPosition.x,character.position.y-ySpeed,floorPosition.z);
//floor checking:
if(character.position.y<floorPosition.y){
ySpeed=0;
jumpState=0;
character.position=new Vector3(floorPosition.x,floorPosition.y,floorPosition.z);
}
}
void MoveCamera(){
//方法一
Camera.main.gameObject.transform.LookAt(character.position);
iTween.MoveUpdate(Camera.main.gameObject,new Vector3(character.position.x,character.position.y,character.position.z-100f),.9f);
//方法二
//iTween.LookUpdate(gameObject,target.position,2);
}
}
using UnityEngine;
using System.Collections;
public class findFloor : MonoBehaviour {
private Vector3 floorPosition;
private RaycastHit hit;
private float rayLength = 300;
private float ySpeed=20;
private float gravity=2f;
private float jumpForce=1f;
public Transform character;
private uint jumpState=0; //0=grounded 1=jumping
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
DetectKeys();
FindFloorAndRotation();
MoveCharacter();
MoveCamera();
}
void DetectKeys(){
//jump:
if (Input.GetKeyDown("space") && jumpState==0) {
ySpeed-=jumpForce;
jumpState=1;
}
}
void FindFloorAndRotation(){
if (Physics.Raycast(character.position,-Vector3.up,out hit, rayLength)){
Debug.DrawRay(character.position, -Vector3.up * hit.distance);
floorPosition=hit.point;
}
}
void MoveCharacter(){
//add gravity:
ySpeed += gravity * Time.deltaTime;
//apply gravity:
character.position=new Vector3(floorPosition.x,character.position.y-ySpeed,floorPosition.z);
//floor checking:
if(character.position.y<floorPosition.y){
ySpeed=0;
jumpState=0;
character.position=new Vector3(floorPosition.x,floorPosition.y,floorPosition.z);
}
}
void MoveCamera(){
//方法一
Camera.main.gameObject.transform.LookAt(character.position);
iTween.MoveUpdate(Camera.main.gameObject,new Vector3(character.position.x,character.position.y,character.position.z-100f),.9f);
//方法二
//iTween.LookUpdate(gameObject,target.position,2);
}
}