Unity2D模拟控制位移

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class PlayerController : MonoBehaviour {
 5 
 6     public float speed = 10f;
 7     public Vector2 playerSize;
 8 
 9 
10     void Update () {
11         float v = Input.GetAxis("Vertical");
12         float h = Input.GetAxis("Horizontal");
13 
14         transform.Translate(new Vector3(h * Time.deltaTime * speed, v * Time.deltaTime * speed, 0f));
15 
16         //检查坐标是否离开屏幕
17         transform.position = transform.position.x < 0 + playerSize.x / 2 ? new Vector3(0 + playerSize.x / 2, transform.position.y, transform.position.z) : transform.position;
18         transform.position = transform.position.x > Screen.width - playerSize.x / 2 ? new Vector3(Screen.width - playerSize.x / 2, transform.position.y, transform.position.z) : transform.position;
19         transform.position = transform.position.y < 0 + playerSize.y / 2 ? new Vector3(transform.position.x, 0 + playerSize.y / 2, transform.position.z) : transform.position;
20         transform.position = transform.position.y > Screen.height - playerSize.y / 2 ? new Vector3(transform.position.x, Screen.height - playerSize.y / 2, transform.position.z) : transform.position;
21 
22     }
23 
24     void OnGUI()
25     {
26         GUI.Label(new Rect(10f, 10f,200f, 100f), transform.position.ToString());
27     }
28 }

控制UI的移动,可以使用在2D类移动上

posted @ 2017-11-17 20:32  lovewaits  阅读(701)  评论(0编辑  收藏  举报