Home>

I'm new to the program.
I want to slow down the enemy's speed when shining light in Unity.

The hit judgment will be given, but the speed will not change.

Corresponding source code

Source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Required when using NavMeshAgent
using UnityEngine.AI;

// Place NavMeshAgent component on the object
[RequireComponent (typeof (NavMeshAgent))]

public class Patrol: MonoBehaviour
{

public Transform [] points;

[SerializeField]
int destPoint = 0;

private NavMeshAgent agent;

Vector3 playerPos;

GameObject player;

float distance;

[SerializeField]
float trackingRange = 3f;

[SerializeField]
float quitRange = 5f;

[SerializeField]
bool tracking = false;

//enemy
[SerializeField] private GameObject enemy;
// Light
[SerializeField] private GameObject lightWepon;
// Variable to hold speed
private float speed = 0.0f;

void Start ()
{
agent = GetComponent();

// Disable autoBraking to move continuously between target points
// (Enemy does not slow down when approaching the target point
agent.autoBraking = true;

GotoNextPoint ();

// Enter the name of the object I want to track
player = GameObject.Find ("Player");

speed = agent.speed;
}

void GotoNextPoint ()
{
// Return when no point is set
if (points.Length == 0)
return;

// Set the enemy to go to the currently set target point
agent.destination = points [destPoint] .position;

// Set the next position in the array as the target point and
// Return to the starting point if necessary
destPoint = (destPoint + 1)% points.Length;
}

void Update ()
{
// Measure the distance between Player and this object
playerPos = player.transform.position;
distance = Vector3.Distance (this.transform.position, playerPos);

if (tracking)
{
// When tracking, stop if the distance is farther than the quit Range
if (distance>quitRange)
{
agent.speed = 4.5f;
tracking = false;
}

// Target Player
agent.destination = playerPos;
}
else else
{
// Start tracking when Player gets closer than tracking Range
if (distance {
agent.speed = 6.0f;
tracking = true;
}

// When the enemy approaches the current target point,
// Select the next target point
if (! agent.pathPending&&agent.remainingDistance<1.5f)
GotoNextPoint ();
return;
}
}

void OnDrawGizmosSelected ()
{
// Show the range of the tracking Range with a red wireframe
Gizmos.color = Color.red;
Gizmos.DrawWireSphere (transform.position, trackingRange);

// Show the quitRange range with a blue wireframe
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere (transform.position, quitRange);
}

public void OnTriggerStay (Collider other)
{
// When the tag of the contacted object is "eye"
if (other.gameObject.tag == "Enemy")
{
// Slow down the enemy
agent.speed-= 2.5f;
//display
Debug.Log ("Hit");// View the log
}
}
}

  • Answer # 1

    Resolved by state and switch processing

Related articles