Skip to content

Instantly share code, notes, and snippets.

@bdecarne
Last active November 4, 2015 18:43
Show Gist options
  • Save bdecarne/28bc99dac484833cbaec to your computer and use it in GitHub Desktop.
Save bdecarne/28bc99dac484833cbaec to your computer and use it in GitHub Desktop.
Unity : click to go
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour {
public GameObject terrain;
public Rigidbody rbody;
public Animator anim;
Vector3 previousPosition;
Vector3 targetPosition;
Quaternion targetRotation;
float speed;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
rbody = GetComponent<Rigidbody>();
speed = 3.0f;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (terrain.GetComponent<Collider>().Raycast(ray, out hit, Mathf.Infinity))
{
targetPosition = hit.point;
//transform.LookAt(hit.point);
targetRotation = Quaternion.LookRotation(targetPosition - transform.position, Vector3.up);
}
}
if (targetPosition != new Vector3(0, 0, 0) && transform.position != targetPosition)
move();
}
void move()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * speed);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment