untiy2D 物体绕某个点跟随鼠标转动

在2D游戏中,有很多类似泡泡龙那样的炮台,跟谁鼠标转动方向,或者出现一条辅助虚线,实现这样的效果代码很简单,但是理解起来非常麻烦,因为涉及了一些数学知识不好理解。

实现的方法有两种,一种是运用向量减法,一种是运用角度计算

角度计算可以参考

http://jingyan.baidu.com/article/fdbd4277164cb9b89e3f48c3.html

这里使用向量减法实现:

代码如下:

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class arrow : MonoBehaviour {
 5     
 6     //测试位置使用
 7     [SerializeField]
 8     private Vector3 tar;
 9     //子弹
10     [SerializeField]
11     private GameObject player;
12     //是否开枪
13     private int fire=0;
14     // Use this for initialization
15     void Start () {
16         //tar=new Vector3(1,0,0);
17         
18     }
19     
20     void Update()
21     {
22         tar = Input.mousePosition;
23         //      //右面朝向鼠标
24         //      transform.right = direction;
25         //      //上面朝向鼠标
26         //      //transform.up = direction;
27         //      //两个方向可以选一个用
28         if (Input.GetMouseButton(0)) {
29             Vector3 target=tar;
30             //          Vector3 target=Camera.main.WorldToScreenPoint(tar);
31             Vector3 obj=Camera.main.WorldToScreenPoint(transform.position);
32             Vector3 direction=target-obj;
33             direction.z=0f;
34             direction=direction.normalized;
35             if (direction.y >= 0.4f) {
36                 transform.up=direction;
37                 fire=1;
38                 print (direction);
39             }else{
40                 fire=0;
41                 print("out");
42             }
43 
44         }
45 
46         if (Input.GetMouseButtonUp(0)) {
47             if (fire==1) {
48                 player.rigidbody2D.velocity=new Vector2(0,1000f*Time.deltaTime);
49             }
50 
51 
52         }
53 
54 
55     }
56 }

 

posted @ 2016-01-18 01:02  安世博  阅读(729)  评论(0)    收藏  举报