添加角色控制器的方式,Physics->Character
Controller
角色控制器能够操作模型移动,通过Move、SimpleMove、
能够使模型上下坡、平移移动等。
SimpleMove:以一定的速度移动。将忽略Y轴上的速度。单位是m/s。重力被自动应用。其返回值真假能够判定是否接触于地面。
Move:通过动力来移动控制器。动力只受限制于碰撞。它将沿着碰撞器滑动。其返回值包含了一些碰撞信息。
using UnityEngine;
using System.Collections;
public class PlayerConsole : MonoBehaviour {
[SerializeField]
private CharacterController _ccll;
[SerializeField]
private float _moveSpeed = 1f;
[SerializeField]
private bool _isApplyGravityAllways = false;//是否一直应用重力作用
[SerializeField]
private EasyJoystick _joy;
[SerializeField]
private Animation _ani;//人物动画
[SerializeField]
private float _defaultSpeed=1f;//默认情况下的速度值
[SerializeField]
private float _dampng=10f;
[SerializeField]
public float pushPower = 2.0f;
void Start ()
{
Init ();
}
void Init()
{
if (_ccll == null)
_ccll = GetComponent<CharacterController> ();
if (_joy == null)
_joy = GameObject.FindObjectOfType<EasyJoystick> ();
if (_ani == null)
_ani = GetComponent<Animation> ();
}
void Update ()
{
if (_isApplyGravityAllways)
A ();
// if (Input.GetKey ("w"))
// {
// _ccll.SimpleMove (_moveSpeed*Vector3.forward);
// }
// if (Input.GetKey ("s"))
// {
// _ccll.SimpleMove (_moveSpeed*Vector3.back);
// }
//_ccll SimpleMove Move
//SimpleMove 自带重力效果,受制于碰撞
//Move不带重力效果,受制于碰撞
//_ccll.SimpleMove(_moveSpeed * -Vector3.forward);
// _ccll.Move(Time.deltaTime * _moveSpeed * -Vector3.forward);
MoveCtr ();
}
void A()
{
_ccll.SimpleMove (Vector3.zero);
}
void MoveCtr()
{
float x = _joy.JoystickAxis.x;
float y = _joy.JoystickAxis.y;
if(x != 0f || y !=0f)
{
Vector3 dir = new Vector3 (x,0,y);
Quaternion rotation = Quaternion.LookRotation (dir);
transform.rotation = Quaternion.Lerp (transform.rotation,rotation,_dampng*Time.deltaTime);
_ccll.SimpleMove (_moveSpeed*transform.forward);
PlayRun();
}
}
void PlayRun()
{
_ani ["Wake"].speed = _moveSpeed / _defaultSpeed;
_ani.CrossFade ("Wake");
}
OnControllerColliderHit is called when the controller hits a collider while performing a Move. 当角色控制器碰到一个可执行移动的碰撞器时,OnControllerColliderHit被调用。 |
void OnControllerColliderHit(ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
if (body == null || body.isKinematic)
return;
if (hit.moveDirection.y < -0.3F)
return;
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
body.velocity = pushDir * pushPower;
}
}
CharacterController con;
float y;
void Start()
{
con = GetComponent<CharacterController>();
}
void Update()
{
if (con.isGrounded)
{
y = 0;
if (Input.GetKeyDown(KeyCode.Space))
{
y = 4f;
}
}
y -= 20 * Time.deltaTime;
con.Move(new Vector3(Input.GetAxis("Horizontal"), y, Input.GetAxis("Vertical")) * 6 * Time.deltaTime);