private var character :CharacterController;
private var speed =0.0;
private var trans:Transform;
private var targetRot:Quaternion;
var rotationSpeed = 90 ;
var pedalImpulse = 3.5;
var maxSpeed = 15;
var decayRate = 0.1;
var jumpSpeed : float = 8.0;
var raycastMask :LayerMask;
function Start()
{
character = GetComponent(CharacterController);
trans= transform ;
}
function pedal()
{
speed += pedalImpulse;
speed = Mathf.Min(speed, maxSpeed);
}
function Update ()
{
var horizontal = Input.GetAxis("Horizontal");
var Vertical = Input.GetAxis("Vertical");
transform.Rotate(0,rotationSpeed*horizontal*Time.deltaTime,0);
if(character.isGrounded)
pedal();
//For normalized vectors Dot returns 1 if they point in exactly the same direction, -1
//if they point in completely opposite directions and zero if the vectors are perpendicular.
var moveDirection = trans.forward*speed*Vertical;
var upright = Vector3.Dot(trans.forward,Vector3.up);//upright >0 是向上行走 <0向下行走
Debug.Log(upright.ToString());
//we want fake gravity when the character becomes upright
//become the characterController dosen`t rotate
//当x>0,sign(x)=1;当x=0,sign(x)=0; 当x<0, sign(x)=-1
//Clamp01 Clamps value between 0 and 1 and returns value.
moveDirection += Vector3.Lerp( Physics.gravity,Mathf.Sign(upright)
* -trans.forward * Physics.gravity.magnitude,
Mathf.Clamp01(Mathf.Abs(upright)));
character.Move(moveDirection*Time.deltaTime);
//旋转角色根据地形法线
var ray = new Ray(trans.position+Vector3.up,-Vector3.up);
var hit : RaycastHit;
if (character.isGrounded && Physics.Raycast(ray,hit,100,raycastMask))
{
var targetRight = Vector3.Cross(hit.normal,trans.forward);
var targetForward = Vector3.Cross(targetRight,hit.normal);
targetRot = Quaternion.LookRotation(targetForward,hit.normal);
}
trans.rotation = Quaternion.Slerp(trans.rotation,targetRot,5*Time.deltaTime);
if(character.isGrounded)
{
if(speed<0.3)
speed=0;
else
{
speed -= decayRate*Time.deltaTime*speed;
}
}
}