2 de jul. de 2017

Following Mouse in 3D

A simple example of an object following the mouse in 3D environment.


using UnityEngine;

public class FollowMouse : MonoBehaviour
{

    public float force;

    Rigidbody ballRigid;
    Ray ray;

    void Start()
    {
        ballRigid = transform.GetComponent<Rigidbody>();
    }

    private void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin, ray.direction * 100, Color.cyan);
    }

    void FixedUpdate()
    {
        RaycastHit hit;
        
        if (Physics.Raycast(ray, out hit, 100))
        {
            if (hit.collider.tag == "Terrain")
            {
                Vector3 direction = hit.point - transform.position;
                ballRigid.AddForce(direction * force);
            }
        }
    }
}

Nenhum comentário: