Created
April 28, 2017 06:51
-
-
Save TeraokaAkihiro/c0afc15747ffebfce51224c8c32d0723 to your computer and use it in GitHub Desktop.
物理挙動でマウスに追尾するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class MouseMover : MonoBehaviour { | |
public float speed; // 大きい程早く動く | |
private GameObject obj; | |
private Rigidbody2D rb; | |
void Start () | |
{ | |
obj = this.gameObject; | |
rb = this.gameObject.GetComponent<Rigidbody2D>(); | |
} | |
void FixedUpdate() | |
{ | |
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // マウスの位置からワールド座標を求める。 | |
Vector2 objPos = obj.transform.position; | |
Vector2 def = pos - objPos; // マウス位置とのベクトル差 | |
rb.velocity = (def / def.magnitude) * speed * Vector2.Distance(objPos, pos); // 速度 = 向き * speed * 距離 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment