滑鼠控制物體移動

來源:互聯網
上載者:User

標籤:data   比例   tar   object   start   小例子   控制   float   upd   

 

 

1.物體移動到滑鼠點擊處

2.物體跟隨滑鼠移動

分為三步:擷取滑鼠位置、轉化為全局座標、物體移動

private Vector3 mopos; 

private Vector3 gamepos;

void Start(){

//物體的全局座標轉化成螢幕座標

//gamepos = Camera.main.WorldToScreenPoint (transform.position);

gamepos = transform.position;

}

 

void Update () {

//物體移動到滑鼠點擊處

if (Input.GetMouseButtonDown (0)) {

mopos = Input.mousePosition;//擷取滑鼠位置

//轉化物體世界z座標為螢幕座標並賦值給滑鼠z座標

mopos.z=Camera.main.WorldToScreenPoint( transform.position).z;

//將需要的滑鼠座標轉化成全局座標

gamepos.x=Camera.main.ScreenToWorldPoint(mopos).x;

gamepos.z=Camera.main.ScreenToWorldPoint(mopos).z;

gamepos.y=transform.position.y;

}

//讓物體移動到座標處

transform.position = Vector3.Lerp (gameObject.transform.position,gamepos,Time.deltaTime*5f);

//朝向某處

//transform.LookAt (gamepos);

}

 

Ps:一個小例子,準星在螢幕中跟隨滑鼠移動

void Updata(){ 

mopos = Input.mousePosition;//擷取滑鼠位置

//調整位置比例

mopos.x /= 823.0f;

mopos.y /= 600.0f;

//移動

transform.position = Vector3.Lerp (gameObject.transform.position,mopos,Time.deltaTime*30f);

}

 

//物體朝向滑鼠方向旋轉

//擷取滑鼠增量 

float h =  Input.GetAxis("Mouse X");

float v = Input.GetAxis("Mouse Y");

//旋轉

transform.Rotate(v, h, 0);

滑鼠控制物體移動

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.