Skip to content

Instantly share code, notes, and snippets.

@TeraokaAkihiro
Created April 28, 2017 06:51
Show Gist options
  • Save TeraokaAkihiro/c0afc15747ffebfce51224c8c32d0723 to your computer and use it in GitHub Desktop.
Save TeraokaAkihiro/c0afc15747ffebfce51224c8c32d0723 to your computer and use it in GitHub Desktop.
物理挙動でマウスに追尾するスクリプト
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