Skip to content

Instantly share code, notes, and snippets.

@ayutaz
Created December 24, 2019 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayutaz/d2cee68be7ac1f9f60260dea3871cc99 to your computer and use it in GitHub Desktop.
Save ayutaz/d2cee68be7ac1f9f60260dea3871cc99 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour {
//Rigidbodyを変数に入れる
Rigidbody rb;
//移動スピード
public float speed = 3f;
//Animatorを入れる変数
private Animator animator;
//ユニティちゃんの位置を入れる
Vector3 playerPos;
private int IsSleep;
 
void Start()
{
//Rigidbodyを取得
rb = GetComponent<Rigidbody>();
//ユニティちゃんのAnimatorにアクセスする
animator = GetComponent<Animator>();
//ユニティちゃんの現在より少し前の位置を保存
playerPos = transform.position;
IsSleep = -1;
}
 
void Update()
{
//A・Dキー、←→キーで横移動
float x = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;
//W・Sキー、↑↓キーで前後移動
float z = Input.GetAxisRaw("Vertical") * Time.deltaTime * speed;
//現在の位置+入力した数値の場所に移動する
rb.MovePosition(transform.position + new Vector3(x, 0, z));
//ユニティちゃんの最新の位置から少し前の位置を引いて方向を割り出す
Vector3 direction = transform.position - playerPos;
//移動距離が少しでもあった場合に方向転換
if (direction.magnitude > 0.01f)
{
//directionのX軸とZ軸の方向を向かせる
transform.rotation = Quaternion.LookRotation(new Vector3
(direction.x, 0, direction.z));
//走るアニメーションを再生
animator.SetBool("walk", true);
}else{
//ベクトルの長さがない=移動していない時は走るアニメーションはオフ
animator.SetBool("walk", false);
}
//ユニティちゃんの位置を更新する
playerPos = transform.position;
//スペースキーやゲームパッドの3ボタンでジャンプ
if (Input.GetButton("Jump"))
{
animator.SetBool("attack", true);
}else{
animator.SetBool("attack",false);
}
if (Input.GetKeyDown(KeyCode.C)){
IsSleep *= -1;
if(IsSleep == 1) animator.SetBool("sleep",true);
else animator.SetBool("sleep",false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment