Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

Mouse click move (not follow the cursor!)

$
0
0
Hi, I'm totally new to Unity and "almost new" to programming in c#, so don't be mad at my incompetence :) I made this little script to make my character move RTS-like - I click somewhere in the screen, world point gets raycasted and so my object follows the left mouse button. What I want is to make it go to clicked destination on it's own. using UnityEngine; using System.Collections; public class movement : MonoBehaviour { public RaycastHit hit; public Ray ray; public Vector3 direction; public float moveSpeed = 0.1f; public int rotateSpeed =50; private Transform PlayerTransform; // Use this for initialization void Start () { PlayerTransform = transform; direction = PlayerTransform.position; } // Update is called once per frame void FixedUpdate () { if(Input.GetMouseButton(0)) { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast (ray, out hit, 100)) { Debug.DrawLine (ray.origin, hit.point, Color.red, 2); Debug.Log ("Raycast succesful"); direction = hit.point; PlayerTransform.position = Vector3.MoveTowards(PlayerTransform.position, hit.point, moveSpeed * Time.deltaTime); Debug.DrawLine(PlayerTransform.position, hit.point, Color.blue, 2); Vector3 targetPoint = hit.point; Quaternion targetRotation = Quaternion.LookRotation(targetPoint - PlayerTransform.position); transform.rotation = Quaternion.Slerp(PlayerTransform.rotation, targetRotation, rotateSpeed * Time.deltaTime); targetPoint.y = 0; } } } } Thanks in advance.

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>