概要
キャラクタを操作するスクリプト作ります。
キーボードとタッチに対応させます
事前にスプライトにキャラ画像と重力、当たり判定はつけています
初期状態はこんな感じです
キャラ移動
移動用スクリプト作成
1.Projectタブからcreate>C# script
2.名前をPlayerに変更(任意)
→ ここでの名前がclass名に入るので、あとから変えるときは変更部分増えちゃいます
3.コーディング
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
//変数定義
public float flap = 550f;
public float scroll = 10f;
float direction = 1f;
Rigidbody2D rb2d;
// Use this for initialization
void Start () {
//コンポーネント読み込み
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
//キャラのy軸のdirection方向にscrollの力をかける
rb2d.velocity = new Vector2(scroll * direction, rb2d.velocity.y);
}
}
4.作成したPlayer.csをキャラクターのInspectorにドラッグ
これで再生すると右に移動出来ます。
scrollの数値を変えると速度が変わります。
directionを-1にすると方向が変わります。
コード読んで意味分からない部分はググったり、なんとなくで覚えといてください。
キーボードで移動方向を変更
float direction = 0f;//1から0へ変更
void Update () {
if (Input.GetKey(KeyCode.RightArrow))
{
direction = 1f;
}else if (Input.GetKey(KeyCode.LeftArrow))
{
direction = -1f;
}else
{
direction = 0f;
}
//キャラのy軸のdirection方向にscrollの力をかける
rb2d.velocity = new Vector2(scroll * direction, rb2d.velocity.y);
}
これで右矢印キーを押すと右へ動き出し、左を押すと左へ動き出し、それ以外の場合は動きません。
スマホのタッチで移動方向を変更
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);
これで移動操作が出来ました!
コードまとめ
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : 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);
}
}