I found a tutorial on youtube which is interacting with NPC and Items. My question is, how can I animate my character once the NPC or item is click. I want the character to move forward to the NPC or item. I'm just confused where should I put the script for animating the character's walk or run maybe.

As you can see, there are 2 boxes which are the NPC and an item. So when I right click the boxes, it should be walk and it will stop beside the npc and item. How would I do that?

enter image description here

WorldInteraction

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class WorldInteraction : MonoBehaviour {
    NavMeshAgent playerAgent;

    void Start() {
        playerAgent = GetComponent<NavMeshAgent>();
    }

    void Update() {
        if (Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) {
            GetInteraction();
        }
    }

    void GetInteraction() {
        Ray interactionRay = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit interactionInfo;
        if(Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity)) {
            GameObject interactedObject = interactionInfo.collider.gameObject;
            if (interactedObject.tag == "Interactable Object") {
                interactedObject.GetComponent<Interactable>().MoveToInteraction(playerAgent);
            } else {
                playerAgent.destination = interactionInfo.point;
            }
        }
    }
}

Interactable

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Interactable : MonoBehaviour {
    public NavMeshAgent playerAgent;

    public virtual void MoveToInteraction(NavMeshAgent playerAgent) {
        this.playerAgent = playerAgent;
        playerAgent.destination = this.transform.position;

        Interact();
    }

    public virtual void Interact() {
        Debug.Log ("Interacting with base class.");
    }
}

NPC

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NPC : Interactable {

    public override void Interact() {
        Debug.Log ("Interacting with NPC.");
    }
}

PlayerController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

        public bool isGrounded;

    private float speed;
        private float rotationSpeed = 75.0f;
    private float moveSpeed = 6f;
    private float moveFB, moveLR;
        public float jumpHeight;
    Rigidbody rb;
        Animator animator;
        CapsuleCollider capcollider;

    public Transform playerCamera, character, centerPoint;
    private float mouseX, mouseY, zoomSpeed = 2, mouseYPosition = 1f;
    public float zoom, zoomMin = -2f, zoomMax = -10f;

    void Start() {
        rb = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
            capcollider = GetComponent<CapsuleCollider>();
            isGrounded = true;

            zoom = -5;
    }

    void Update() {
        zoom += Input.GetAxis ("Mouse ScrollWheel") * zoomSpeed;

            if (zoom > zoomMin)
            {
                    zoom = zoomMin;
            }
            if (zoom < zoomMax)
            {
                zoom = zoomMax;
            }
        playerCamera.transform.localPosition = new Vector3 (0, 0, zoom);

        mouseX += Input.GetAxis ("Mouse X");
            mouseY -= Input.GetAxis ("Mouse Y");
            playerCamera.rotation = Quaternion.Euler(0, mouseX, 0);

        mouseY = Mathf.Clamp (mouseY, 2, 60f);
            playerCamera.LookAt(centerPoint);
            centerPoint.localRotation = Quaternion.Euler (mouseY, mouseX, 0);

        moveFB = Input.GetAxis ("Vertical") * moveSpeed;
            moveLR = Input.GetAxis ("Horizontal") * moveSpeed;

            //transform.Translate(0, 0, moveFB);
            //transform.Rotate(0, moveLR, 0);

        Vector3 movement = new Vector3 (moveLR, 0, moveFB);
            movement = character.rotation * movement;
            character.GetComponent<CharacterController>().Move(movement * Time.deltaTime);
            centerPoint.position = new Vector3(character.position.x, character.position.y + mouseYPosition, character.position.z);

            /*if(Input.GetKey(KeyCode.Space) && isGrounded == true)
            {
                    rb.AddForce(0, jumpHeight, 0);
                    animator.SetTrigger("isJumping");
                    isGrounded = false;
            }*/

            if (Input.GetKey(KeyCode.LeftShift))
            {
                    if (Input.GetAxis("Vertical") > 0)
                    {
                        moveSpeed = 8f;
                        Quaternion turnAngle = Quaternion.Euler(0, centerPoint.eulerAngles.y, 0);
                        character.rotation = Quaternion.Slerp(character.rotation, turnAngle, Time.deltaTime * rotationSpeed);
                        animator.SetBool("isRunning", true);
                    }
                    else if (Input.GetAxis("Vertical") < 0) 
                    {
                        moveSpeed = 4f;
                        Quaternion turnAngle = Quaternion.Euler(0, centerPoint.eulerAngles.y, 0);
                        character.rotation = Quaternion.Slerp(character.rotation, turnAngle, Time.deltaTime * rotationSpeed);
                        animator.SetBool("isBack", true);
                    }
                    else if (Input.GetAxis("Vertical") == 0 && Input.GetAxis("Horizontal") == 0)
                    {
                        animator.SetBool("isWalking", false);
                        animator.SetBool("isRunning", false);
                        animator.SetBool("isBack", false);
                    }
            }
            else
            {
                    if (Input.GetAxis("Vertical") > 0)
                    {
                        moveSpeed = 4f;
                        Quaternion turnAngle = Quaternion.Euler(0, centerPoint.eulerAngles.y, 0);
                        character.rotation = Quaternion.Slerp(character.rotation, turnAngle, Time.deltaTime * rotationSpeed);
                        animator.SetBool("isWalking", true);
                    }
                    else if (Input.GetAxis("Vertical") < 0) 
                    {
                        moveSpeed = 4f;
                        Quaternion turnAngle = Quaternion.Euler(0, centerPoint.eulerAngles.y, 0);
                        character.rotation = Quaternion.Slerp(character.rotation, turnAngle, Time.deltaTime * rotationSpeed);
                        animator.SetBool("isBack", true);
                    }
                    else if (Input.GetAxis("Vertical") == 0 && Input.GetAxis("Horizontal") == 0)
                    {
                        animator.SetBool("isWalking", false);
                        animator.SetBool("isRunning", false);
                        animator.SetBool("isBack", false);
                    }
            }
    }
}
New contributor
J.Wujeck is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Game you're developing looks pretty cool. I'm a little unclear what you're asking for though, because animations refers to the mesh being animated, but you seem to be talking about updating the characters position in the game-world, which is handled separately from the animation (There is a way to apply Root movement with animation - which means the animation files have positional data baked into them, but it would be better to handle the positional movement and then separately handle switching animation clips depending on that movement (and/or other factors such as jumping, attacking etc). – Super MegaBroBro Dec 7 at 14:16
  • What should I do? Is it possible to interact with NPC by pressing a key? For example, assume that the character is in front of NPC or object and then a text dialog will pop up that the character will press a key to interact with NPC? Sample text is "Press F to interact"? – J.Wujeck Dec 7 at 16:40
  • yes it is certainly possible to do that. There are many ways but one might be to use a collision box (set as a trigger) on the NPC so you know if the player is inside it. You can also use whats called Raycasting. The upon button press you call a method you make which will only work if you are inside the collision box ... NOTE I am still learning myself, and theres probably a lot better ways to handle it, but its a starting point for beginners like us. The method you call and the way you interact with the NPC (ie opening dialog etc) depends on you and how you code it. – Super MegaBroBro Dec 7 at 19:10
  • How will I check if the character is inside the NPC or item collider? What code should I update? – J.Wujeck Dec 8 at 0:43

Your Answer

J.Wujeck is a new contributor. Be nice, and check out our Code of Conduct.

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.