Unityでキャラを動かしているときにGetKeyとGetAxisの二つの動かし方(コードで)があることがわかりました.
しかし,よく何が違うのが変わりません....
何かAxisを使う方は力を加えるってことくらいしか
わからないので二つとも書いて試してみることにしました.
コードはこちらのサイトを参考にしています.
こちらが,GetKeyを使った移動コードです.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerkey : MonoBehaviour {
//変数定義
public float flap = 550f;
public float scroll = 10f;//速度
float direction = 0f;
Rigidbody2D rb2d;
// Use this for initialization
void Start () {
//コンポーネント読み込み
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
//キーボード操作
if (Input.GetKey(KeyCode.RightArrow))
{
direction = 1f;
}else if (Input.GetKey(KeyCode.LeftArrow))
{
direction = -1f;
}else
{
direction = 0f;
}
//スマホ操作
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
//画面右半分をタッチしていたら
if(touch.position.x > Screen.width * 0.5f)
{
direction = 1f;
//画面左半分をタッチしていたら
}else if (touch.position.x < Screen.width * 0.5f)
{
direction = -1f;
}
else
{
direction = 0f;
}
}
//キャラのy軸のdirection方向にscrollの力をかける
rb2d.velocity = new Vector2(scroll * direction, rb2d.velocity.y);
}
}
で,こちらがGetAxisを使ったコードです.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float flag=1000f;
private Rigidbody2D rb2d;
bool jump = false;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update(){
if(Input.GetKeyDown("space") && !jump){
rb2d.AddForce(Vector2.up*flag);
jump = true;
}
}
void FixedUpdate(){
float moveHorizontal = Input.GetAxis("Horizontal");
//float moveVertical = Input.GetAxis("Vertical");
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Horizontal");
Vector2 movementX = new Vector2(moveHorizontal,0);
//Vector2 movementY = new Vector2(0,moveVertical);
rb2d.AddForce(movementX * speed);
//rb2d.AddForce(movementY * speed);
Vector3 scale = transform.localScale;
if(x >= 0){
scale.x = 2;
}else{
scale.x = -2;
}
transform.localScale = scale;
}
void OnCollisionEnter2D(Collision2D other){
if(other.gameObject.CompareTag("ground")){
jump = false;
}
}
}
実際に動かしてみると全然違いますが,どちらがいいと決めるとなるとなかなか難しいですね!!