- Home /
Question by
FatDonutCop · Jan 21, 2017 at 06:49 AM ·
c#raycast
How do I make the object that I touched move to a location
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class TEST : MonoBehaviour
{
public int hitInfo;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit)
{
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
if (hitInfo.transform.gameObject.tag == "Soldier1")
{
MoveUnit();
}
else
{
}
}
else
{
Debug.Log("No hit");
}
}
}
public Transform target;
public float speed;
public void MoveUnit()
{
}
}
Comment
Answer by EDevJogos · Jan 21, 2017 at 01:28 PM
Create a script for the object like Soldier.cs and let him handle its own movement, set a method MoveTo(Transform target)
and a bool move
when you raycast on your TEST script just call hitinfo.GetComponent<Soldier>().MoveTo(target);
then the solider MoveTo()
will set the move bool to true and assing the target with the target you passed as a parameter, then in the Update()
if move is true do a Translate to the target position.