ボタンを押した時、移動・回転させる処理を作成します。

画面上にボタンを配置してバー(プレイヤー)にスクリプトをアタッチします。
public Rigidbody2D Body { get; private set; }
public RectTransform RectTransform { get; private set; }
bool right = false;
bool left = false;
bool right_Rotate = false;
bool left_Rotate = false;
// 4つのボタンを押しているか否かのbool値を設定
void Awake()
{
this.Body = gameObject.GetComponent<Rigidbody2D>();
this.RectTransform = gameObject.GetComponent<RectTransform>();
}//このオブジェクトの位置情報を取得
void Update()
{
if (right)
{
MoveRight();
//bool値rightが真なら右に移動する処理を行う
}
else if (left)
{
MoveLeft();
}
else if (right_Rotate)
{
RightRotate();
//回転
}
else if (left_Rotate)
{
LeftRotate();
}
}
public void rDown()
{
//右ボタンを押している間、bool値rightを真にする
right = true;
}
public void rUp()
{
//右ボタンを離した時、bool値rightを偽にする
right = false;
}
public void lDown()
{
left = true;
}
public void lUp()
{
left = false;
}
public void rRotateDown()
{
right_Rotate = true;
}
public void rRotateUp()
{
right_Rotate = false;
}
public void lRotateDown()
{
left_Rotate = true;
}
public void lRotatePushUp()
{
left_Rotate = false;
}
public void MoveRight()
{
// 右ボタンが押している間バーを移動させる
// ただしゲームエリア外に出て行かないよう移動上限を決める
var currentX = this.RectTransform.localPosition.x;
// 今の位置から右に10移動
// 260で止める
var newX = Mathf.Min(currentX + 10, 260);
var pos = new Vector3(newX, this.RectTransform.localPosition.y, this.RectTransform.localPosition.z);
this.RectTransform.localPosition = pos;//今の位置を取得する
}
public void MoveLeft()
{
var currentX = this.RectTransform.localPosition.x;
var newX = Mathf.Max(currentX - 10, -260);
var pos = new Vector3(newX, this.RectTransform.localPosition.y, this.RectTransform.localPosition.z);
this.RectTransform.localPosition = pos;
}
public void RightRotate()
{
transform.Rotate(0, 0, -3);
}
public void LeftRotate()
{
transform.Rotate(0, 0, 3);
}
ボタンにEvent Triggerを追加。Add New Eventからオブジェクトと起こしたいイベント関数を設定する。
コメント