当前位置:网站首页>Unity3d RPG implementation (medium)
Unity3d RPG implementation (medium)
2022-07-03 03:11:00 【Sunny summer.】
Set the basic attributes and status of the enemy
download rpg monster Package and import , Then we need to update the material . And write the code .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public enum EnemyStates { GUARD,PATROL,CHASE,DEAD}
[RequireComponent(typeof(NavMeshAgent))]
public class EnemyController : MonoBehaviour
{
public EnemyStates enemyStates;
private NavMeshAgent agent;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
SwitchState();
}
void SwitchState()// Realize a simple state switch
{
switch (enemyStates)
{
case EnemyStates.GUARD:
break;
case EnemyStates.PATROL:
break;
case EnemyStates.CHASE:
break;
case EnemyStates.DEAD:
break;
}
}
}
add to tag and layer.
It is necessary to realize occlusion elimination for the enemy , So in pipeline Except player More than a enemy that will do .
Attack the enemy
Set another click event :
stay playerController Register the function in :
MoveToEnemy Functions like this can be used alt+enter fill
have access to alt+enter Realization
Add attack animation to players , Note that the switch from attack to running must be exit time Set to 1, Only in this way can the animation be played .
StopAllCoroutines();// So that the character can also click to go to other places in the process of moving towards the goal , Interrupt operation
agent.isStopped = false;// Add this sentence , It solves the problem that characters cannot act once they attack
Later on playercontroller Code to move towards the enemy after the attack :
void EventAttack(GameObject target)
{
if (target != null)
{
attackTarget = target;
StartCoroutine(MoveToAttackTarget());
}
}
IEnumerator MoveToAttackTarget()
{
// In order to prevent the next time after this click agent Unable to act , Use recovery at the beginning of this click
agent.isStopped = false;
transform.LookAt(attackTarget.transform);
while (Vector3.Distance(transform.position, attackTarget.transform.position) > 1)
{
agent.destination = attackTarget.transform.position;
yield return null;
}
// When arriving at the designated place , command agent stop it
agent.isStopped = true;
// The attack has cd Time
if (lastAttackTime < 0)
{
animator.SetTrigger("Attack");
lastAttackTime = 0.5f;
}
}
}
The way to go to the enemy is through coordination , Join in lastAttackTime Used to attack cd The cooling of .
Because the navigation system comes with destination It's going to keep moving , So we need to realize when the distance is 1 When you stop moving, use agent
isStopped by true To execute . Corresponding , The initial needs of this process are set isStop by false.
bug:
After executing the above code, you will find , Once the character attacks the enemy, he can no longer move by clicking on the ground , This is because isStopped Set up in order to false, So you need to click on the ground to move
effect :
( The mouse pointer cannot be displayed )
here MouseManger
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System;
//[System.Serializable]
//public class EventVector3 : UnityEvent<Vector3> { }// Declare an event
public class MouseManager : MonoBehaviour
{
//public EventVector3 OnMouseClicked;
public event Action<Vector3> OnMouseClicked;
public event Action<GameObject> OnEnemyClicked;
RaycastHit hitInfo;
public static MouseManager Instance;
public Texture2D point, doorway, attack, target, arrow;
private void Awake()
{
if (Instance != null) Destroy(gameObject);
Instance = this;
}
private void Update()
{
SetCursorTexture();
MouseControl();
}
void SetCursorTexture()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// Get rays
// Output the ray information to hitInfo
if (Physics.Raycast(ray, out hitInfo)) {
switch (hitInfo.collider.gameObject.tag)
{
case "Ground":
Cursor.SetCursor(target, new Vector2(16,16), CursorMode.Auto);
break;
case "Enemy":
Cursor.SetCursor(attack, new Vector2(16, 16), CursorMode.Auto);
break;
}
}
}
void MouseControl()
{
if (Input.GetMouseButtonDown(0) && hitInfo.collider != null)
{
if (hitInfo.collider.CompareTag("Ground"))
{
OnMouseClicked?.Invoke(hitInfo.point);
// Click to send the location to OnMouseClicked This event registers the function and calls
}
if (hitInfo.collider.CompareTag("Enemy"))
{
OnEnemyClicked?.Invoke(hitInfo.collider.gameObject);
// Click to send the location to OnMouseClicked This event registers the function and calls
}
}
}
}
Time setting isStopped by true.
And then there's another one bug, Cannot move when entering the state of attacking the enemy , You can only move after the attack , Add here :
Then you can attack the enemy :
Camera's Freelook
First the cvm Turn off the , Enable cinemachine Medium freelook
Drag the character in , At this point, you can see three red circles
There are three circles , It means that the camera can rotate freely in these three dimensions :
Running the game can realize the perspective switching of the scene .
We will y The movement of the axis is realized with the mouse wheel ( This name comes from setting Inside input manager Name setting in )
Change the size of three circles
The actual use effect of the three circles is as follows :
If you want to keep the value in the modification :
If you want the camera to follow the direction of the person when the person moves, you can modify bindingmode:
Here is a small detail , Add some TODO: FIXME: As a to-do
The pursuit of the enemy
Add code to detect players for enemies :
bool FoundPlayer()
{
var colliders = Physics.OverlapSphere(transform.position, sightRadius);
foreach(var target in colliders)
{
if (target.CompareTag("Player"))
{
return true;
}
}
return false;
}
Call when switching state :
Don't forget to add collision bodies to players
add , We are here for hierarchy Medium player and enemy It's been modified , Want these changes to cover project The inside can be used override.
Next, we'll implement chase, Before writing, you can record what you want to do in this way , Convenient sorting logic .
边栏推荐
- How to return ordered keys after counter counts the quantity
- 45 lectures on MySQL [index]
- MySql实战45讲【全局锁和表锁】
- The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
- BigVision代码
- 处理数据集,使用LabelEncoder将所有id转换为从0开始
- PHP constructor with parameters - PHP constructor with a parameter
- Thunderbolt Chrome extension caused the data returned by the server JS parsing page data exception
- The process of connecting MySQL with docker
- 后管中编辑与预览获取表单的值写法
猜你喜欢
Left connection, inner connection
el-tree搜索方法使用
Le processus de connexion mysql avec docker
【PyG】理解MessagePassing过程,GCN demo详解
Use of El tree search method
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
Three. JS local environment setup
Vs Code configure virtual environment
Add some hard dishes to the interview: how to improve throughput and timeliness in delayed task scenarios!
Practice of traffic recording and playback in vivo
随机推荐
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
分布式事务
Edit and preview in the back pipe to get the value writing method of the form
The idea cannot be loaded, and the market solution can be applied (pro test)
com.fasterxml.jackson.databind.exc.InvalidFormatException问题
Model transformation onnx2engine
Vs 2019 configure tensorrt to generate engine
C language beginner level - pointer explanation - paoding jieniu chapter
MySql实战45讲【事务隔离】
Serious security vulnerabilities reported by moxa mxview network management software
Spark on yarn resource optimization ideas notes
销毁Session和清空指定的属性
Check log4j problems using stain analysis
基于Qt的yolov5工程
Add some hard dishes to the interview: how to improve throughput and timeliness in delayed task scenarios!
How to implement append in tensor
js根据树结构查找某个节点的下面的所有父节点或者子节点
el-tree搜索方法使用
Find the storage address of the elements in the two-dimensional array
Force freeing memory in PHP