Last active
November 4, 2015 18:43
-
-
Save bdecarne/28bc99dac484833cbaec to your computer and use it in GitHub Desktop.
Unity : click to go
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; | |
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