hi,
I’ve been trying to change my game from a click to move to a touch to move. I used the live training video to create the controls for the click to move game. But I’m having difficulty with converting the script to a touch system.I am not the best at coding. Any help would be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
using UnityEngine.AI;
public class ClickToMove : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public float shootDistance = 10f;
public float shootRate = .5f;
public PlayerShooting shootingScript;
private Animator anim;
private UnityEngine.AI.NavMeshAgent navMeshAgent;
private Transform targetedEnemy;
private Ray shootRay;
private RaycastHit shootHit;
private bool walking;
private bool enemyClicked;
private float nextFire;
// Use this for initialization
void Awake ()
{
anim = GetComponent<Animator> ();
navMeshAgent = GetComponent<UnityEngine.AI.NavMeshAgent> ();
}
// Update is called once per frame
void Update ()
{
for (int i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch (i).phase == TouchPhase.Began) {
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
if (hit.collider.CompareTag("Enemy"))
{
targetedEnemy = hit.transform;
enemyClicked = true;
}
else
{
walking = true;
enemyClicked = false;
navMeshAgent.destination = hit.point;
navMeshAgent.Resume();
}
}
}
if (enemyClicked) {
MoveAndShoot();
}
if (navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance) {
if (!navMeshAgent.hasPath || Mathf.Abs (navMeshAgent.velocity.sqrMagnitude) < float.Epsilon)
walking = false;
} else {
walking = true;
}
anim.SetBool ("IsWalking", walking);
}
}
}
private void MoveAndShoot()
{
if (targetedEnemy == null)
return;
navMeshAgent.destination = targetedEnemy.position;
if (navMeshAgent.remainingDistance >= shootDistance) {
navMeshAgent.Resume();
walking = true;
}
if (navMeshAgent.remainingDistance <= shootDistance) {
transform.LookAt(targetedEnemy);
Vector3 dirToShoot = targetedEnemy.transform.position - transform.position;
if (Time.time > nextFire)
{
nextFire = Time.time + shootRate;
shootingScript.Shoot(dirToShoot);
}
navMeshAgent.Stop();
walking = false;
}
}
}