Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Click to move game

Discussion in 'Navigation' started by Adham_star, Nov 6, 2015.

  1. Adham_star

    Adham_star

    Joined:
    Aug 27, 2015
    Posts:
    2
    Hi friends, I'm trying to make a click to move game, but during rum time the player sometimes fails to transit from idle to walking animation, and he moves while in idle animation. Is there any solution for this problem?
    .... Here is my code:

    using UnityEngine;
    using System.Collections;

    public class AgentWalkScript : MonoBehaviour
    {

    int isWalkingHash = Animator.StringToHash("IsWalking");
    int shootingHash = Animator.StringToHash("Shooting");
    float nextFire;
    public float shootRate = 2f;
    bool enemyClicked;
    Transform targetedEnemy;
    Transform destination;
    PlayerShooting playerShooting;
    Vector3 dirToShoot;

    NavMeshAgent agent;

    Animator anim;
    public int damagePerShot = 20;
    public float timeBetweenBullets = 0.15f;
    public float range = 100f;
    float timer;
    Ray shootRay;
    RaycastHit shootHit;
    bool walking;
    //int shootableMask;

    //float effectsDisplayTime = 0.2f;

    void Awake ()
    {
    agent = gameObject.GetComponent<NavMeshAgent>();
    anim = GetComponent<Animator> ();
    playerShooting = GetComponentInChildren<PlayerShooting> ();

    //agent.SetDestination(destination.position);
    }

    void Update()
    {
    Ray screenRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Input.GetMouseButton(0))
    {
    if (Physics.Raycast(screenRay, out hit,100))
    {
    walking = true;
    agent.SetDestination(hit.point);
    anim.SetBool(isWalkingHash,walking);
    transform.LookAt(hit.point);
    }

    if (hit.collider.CompareTag("Enemy"))
    {
    targetedEnemy = hit.transform;
    enemyClicked = true;
    }
    else
    {
    anim.SetBool(isWalkingHash,walking);
    anim.SetBool(shootingHash,false);
    enemyClicked = false;
    agent.destination = hit.point;
    agent.Resume();

    }

    }

    if (enemyClicked) {
    agent.Stop();
    ShootMovement();

    }
    if(agent.remainingDistance<=.1)
    {
    walking = false;
    anim.SetBool(isWalkingHash,walking);
    }
    }
    void ShootMovement()
    {
    if (targetedEnemy == null) {
    return;
    }
    walking = false;
    anim.SetBool(shootingHash,true);
    anim.SetBool(isWalkingHash,walking);
    transform.LookAt(targetedEnemy);
    dirToShoot = targetedEnemy.transform.position - transform.position;
    if (Time.time > nextFire)
    {
    nextFire = Time.time + shootRate;
    playerShooting.Shoot(dirToShoot);
    }


    }



    }