Skip to content

Instantly share code, notes, and snippets.

@TORISOUP
Last active August 29, 2015 14:15
Show Gist options
  • Save TORISOUP/d1ece16bf01c0a4c61c3 to your computer and use it in GitHub Desktop.
Save TORISOUP/d1ece16bf01c0a4c61c3 to your computer and use it in GitHub Desktop.
Move and AnimationChange
private CharacterController characterController;
bool IsJumpable
{
get
{
if (!characterController.isGrounded)
{
return false;
}
return (currentBaseState.nameHash == locoState || currentBaseState.nameHash == idleState) && !anim.IsInTransition(0);
}
}
void Start()
{
characterController = GetComponent <CharacterController>();
}
void Update()
{
//入力
var inputVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
var isJumpButtonPushed = Input.GetButtonDown("Jump");
//移動処理
Move(inputVector, isJumpButtonPushed);
//アニメーション
AnimationChange(isJumpButtonPushed);
}
/// <summary>
/// 移動処理
/// </summary>
/// <param name="moveDirection">移動方向</param>
/// <param name="isJump">ジャンプするか</param></param>
void Move(Vector3 moveDirection, bool isJump)
{
//現在の落下速度
var currentYSpeed = characterController.velocity.y;
//現在の落下速度に重力を加算したもの
var gravityAddYSpeed = currentYSpeed + Physics.gravity.y * Time.deltaTime;
//ジャンプ条件を満たしたらジャンプ速度追加
var jumpSpeed = (isJump && IsJumpable) ? jumpPower : 0;
//最終的な移動速度
var moveVelocity = new Vector3(moveDirection.x * forwardSpeed,
gravityAddYSpeed + jumpSpeed,
moveDirection.z * forwardSpeed);
//移動
characterController.Move(moveVelocity * Time.deltaTime);
}
/// <summary>
/// アニメーション管理
/// </summary>
/// <param name="isJump">If set to <c>true</c> is jump.</param>
void AnimationChange(bool isJump)
{
//-ジャンプアニメーションの再生
anim.SetBool("Jump", isJump && IsJumpable);
//-歩きアニメーションの速度変更
//現在の移動速度
var currentVelocity = characterController.velocity;
//水平移動速度
var horizontalVelocity = new Vector3(currentVelocity.x, 0, currentVelocity.z);
//移動速度
var horizontalSpeed = horizontalVelocity.magnitude;
//アニメーション変更
anim.SetFloat("Speed", horizontalSpeed);
//-向きの変更
var horizontalDirection = horizontalVelocity.normalized;
var lookAtQuaternion = Quaternion.LookRotation(horizontalDirection);
transform.rotation = Quaternion.Lerp(transform.rotation, lookAtQuaternion, Time.deltaTime * 10.0f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment