thieumao

Unity - Di chuyen va xoay theo click chuot

Aug 31st, 2015
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class theLastOneBehaviour : MonoBehaviour {
  5.  
  6.     private Vector3 clickPos;  // vi tri click left mouse
  7.     public float speed = 5.0f;
  8.  
  9.     // Use this for initialization
  10.     void Start () {
  11.         clickPos = transform.position;
  12.     }
  13.    
  14.     // Update is called once per frame
  15.     void Update () {
  16.         MovetheLastOne ();
  17.         Rotation();
  18.     }
  19.  
  20.     void MovetheLastOne(){
  21.         // bat su kien click chuot trai
  22.         if (Input.GetMouseButton (0)) {
  23.             // Camera.main.ScreenToWorldPoint --> Chuyen Toa do man hinh thanh toa do 3 chieu
  24.             // Input.mousePosition --> Lay toa do man hinh
  25.             clickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  26.             // giu toa do z
  27.             clickPos.z = transform.position.z;
  28.         }
  29.  
  30.         // di chuyen tu vi tri hien tai toi clickPos
  31.         transform.position = Vector3.MoveTowards (transform.position, clickPos, Time.deltaTime * speed);
  32.     }
  33.  
  34.     void Rotation(){
  35.         // vi tri click chuot tren man hinh
  36.         Vector3 screenPos = Input.mousePosition;
  37.         // doi sang tao do chieu 3 chieu
  38.         Vector3 worldPos = Camera.main.ScreenToWorldPoint (screenPos);
  39.  
  40.         float dx = transform.position.x - worldPos.x; // do lech truc x
  41.         float dy = transform.position.y - worldPos.y; // do lech truc y
  42.  
  43.         float radAngle = Mathf.Atan2 (dy, dx);
  44.         float degAngle = radAngle * Mathf.Rad2Deg; // doi radian sang degree (do)
  45.         // xoay - Tinh Quaternion
  46.         Quaternion qua = Quaternion.Euler (new Vector3(0,0,degAngle+90));
  47.         transform.rotation = qua;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment