当前位置:网站首页>[unity3d] blood bar (HP)
[unity3d] blood bar (HP)
2022-07-22 10:57:00 【little_ fat_ sheep】
1 Demand fulfillment
human-computer interaction Input It realizes the control of tank movement through the keyboard , Control the tank to launch shells through the mouse , On this basis, this paper will , Increase blood bar (HP) function . After the shell hit ,HP The value will decrease , Therefore, it needs to be applied to Rigid body components Rigidbody and Impactor assembly Collider; When attacking the enemy from different angles , The enemy's blood bar is always facing the camera , So we need to use The camera follows ; Blood bar pass Image Show , So we need to use UGUI And Image; The player's blood bar is always displayed in the upper left corner of the screen , So we need to use Anchor point .
1) Demand fulfillment
- Front and back arrow keys or W, S Key to control the player to move forward or backward ;
- Left and right arrow keys or A, D Key to control the player to turn left and right ;
- The left mouse button or the space bar controls the player to fire shells ;
- The player's blood bar is displayed in the upper left corner of the screen ;
- The position of the camera above the back of the player , Always follow the player , Look directly in front of the player ;
- When players move , The enemy turns to the player , When the angle away from the player is less than 5° when , Fire a shell ;
- The enemy's blood bar is displayed above it , And always look at the camera .
2) It's about the technology stack
- Transform Components
- human-computer interaction
- Rigid body components Rigidbody
- Impactor assembly Collider
- The camera follows
- UGUI And Image
- Canvas Rendering mode and anchor
2 The game object
1) Game interface
2) GameObject hierarchy
3 Transform Component parameters
1) The player Transform Component parameters
Name | Type | Position | Rotation | Scale | Color/Texture |
Player | Empty | (0, 0.25, -5) | (0, 0, 0) | (1, 1, 1) | #228439FF |
Botton | Cube | (0, 0, 0) | (0, 0, 0) | (2, 0.5, 2) | #228439FF |
Top | Cube | (0, 0.5, 0) | (0, 0, 0) | (1, 0.5, 1) | #228439FF |
Gun | Cylinder | (0, 0, 1.5) | (90, 0, 0) | (0.2, 1, 0.4) | #228439FF |
FirePoint | Empty | (0, 1.15, 0) | (0, 0, 0) | (1, 1, 1) | —— |
Add :Player Game object added rigid body components , And modify it Mass = 100,Drag = 1,AngularDrag = 0.1,Freeze Rotation The admission X and Z.
2) The player HP RectTransform Component parameters
Name | Type | Rect | Width/Height | Pos | Color/Texture |
PlayerHP | Canvas | —— | —— | —— | —— |
Panel | Panel | (0, 0, 0, 0) | —— | (-, -, 0) | #FFFFFF00 |
HealthBG | Image | (0, 0.25, -5) | (200, 20) | (125, -30, 0) | #FFFFFFFF |
Health | Image | (0, 0.25, -5) | (200, 20) | (125, -30, 0) | #FF2230FF |
Add : The player PlayerHP Of Canvas The rendering mode is Screen Space - Overlay,Health Of ImageType Set to Filled,Fill Method Set to Horizontal.
3) The enemy Transform Component parameters
Name | Type | Position | Rotation | Scale | Color/Texture |
Enemy | Empty | (0, 0.25, 5) | (0, 180, 0) | (1, 1, 1) | #15D3F9FF |
Botton | Cube | (0, 0, 0) | (0, 0, 0) | (2, 0.5, 2) | #15D3F9FF |
Top | Cube | (0, 0.5, 0) | (0, 0, 0) | (1, 0.5, 1) | #15D3F9FF |
Gun | Cylinder | (0, 0, 1.5) | (90, 0, 0) | (0.2, 1, 0.4) | #15D3F9FF |
FirePoint | Empty | (0, 1.15, 0) | (0, 0, 0) | (1, 1, 1) | —— |
Add :Enemy Game object added rigid body components , And modify it Mass = 100,Drag = 0.5,AngularDrag = 0.1,Freeze Rotation The admission X and Z.
4) The enemy HP RectTransform Component parameters
Name | Type | Width/Height | Pos | Color/Texture |
HP | Canvas | (2, 0.2) | (0, 0.85, 0) | —— |
HealthBG | Image | (2, 0.2) | (0, 0, 0) | #FFFFFFFF |
Health | Image | (2, 0.2) | (0, 0, 0) | #FF2230FF |
Add : The enemy HP Of Canvas The rendering mode is World Space,Health Of ImageType Set to Filled,Fill Method Set to Horizontal.
5) Ground and shells Transform Component parameters
Name | Type | Position | Rotation | Scale | Color/Texture |
Plane | Plane | (0, 0, 0) | (0, 0, 0) | (10, 10, 10) | GrassRockyAlbedo |
Bullet | Sphere | (0, 0.5, -5) | (0, 0, 0) | (0.3, 0.3, 0.3) | #228439FF |
Add : The shell is dragged as a preset body to Assets/Resources/Prefabs Under the table of contents , And added rigid body components .
3 Script components
1)CameraController
CameraController.cs
using UnityEngine;
public class CameraController : MonoBehaviour {
private Transform player; // The player
private Vector3 relaPlayerPos; // The position of the camera in the player's coordinate system
private float targetDistance = 15f; // The camera looks at the position in front of the player
private void Start() {
relaPlayerPos = new Vector3(0, 4, -8);
player = GameObject.Find("Player/Top").transform;
}
private void LateUpdate() {
CompCameraPos();
}
private void CompCameraPos() { // Calculate camera coordinates
Vector3 target = player.position + player.forward * targetDistance;
transform.position = transformVecter(relaPlayerPos, player.position, player.right, player.up, player.forward);
transform.rotation = Quaternion.LookRotation(target - transform.position);
}
// Seeking for origin Origin , locX, locY, locZ Is the vector in the local coordinate system of the coordinate axis vec The corresponding vector in the world coordinate system
private Vector3 transformVecter(Vector3 vec, Vector3 origin, Vector3 locX, Vector3 locY, Vector3 locZ) {
return vec.x * locX + vec.y * locY + vec.z * locZ + origin;
}
}
explain : CameraController The script component is hung on MainCamera On the object of the game .
2)PlayerController
PlayerController.cs
using System;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private Transform firePoint; // Firing point
private GameObject bulletPrefab; // Shell preset
private float tankMoveSpeed = 4f; // Tank moving speed
private float tankRotateSpeed = 2f; // The turning speed of the tank
private float fireWaitTime = float.MaxValue; // The waiting time since the last firing
private float bulletCoolTime = 0.15f; // Shell cooling time
private void Start() {
firePoint = transform.Find("Top/Gun/FirePoint");
bulletPrefab = (GameObject) Resources.Load("Prefabs/Bullet");
}
private void Update() {
fireWaitTime += Time.deltaTime;
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
Move(hor, ver);
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) {
Fire();
}
}
private void Move(float hor, float ver) { // Tank movement
if (Math.Abs(hor) > 0.1f || Math.Abs(ver) > 0.1f) {
GetComponent<Rigidbody>().velocity = transform.forward * tankMoveSpeed * ver;
GetComponent<Rigidbody>().angularVelocity = Vector3.up * tankRotateSpeed * hor;
}
}
private void Fire() { // fire
if (fireWaitTime > bulletCoolTime) {
BulletInfo bulletInfo = new BulletInfo("PlayerBullet", Color.red, transform.forward, 10f, 15f);
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
bullet.AddComponent<BulletController>().SetBulletInfo(bulletInfo);
fireWaitTime = 0f;
}
}
}
explain : PlayerController The script component is hung on Player On the object of the game .
3)EnemyController
EnemyController.cs
using UnityEngine;
using UnityEngine.UI;
public class EnemyController : MonoBehaviour {
private Transform target; // The goal is
private Transform top; // Gun head
private Transform firePoint; // Firing point
private Transform hp; // Blood strip
private GameObject bulletPrefab; // Shell preset
private float rotateSpeed = 0.4f; // The turning speed of the tank
private float fireWaitTime = float.MaxValue; // The waiting time since the last firing
private float bulletCoolTime = 1f; // Shell cooling time
private void Start () {
target = GameObject.Find("Player/Top").transform;
top = transform.Find("Top");
firePoint = transform.Find("Top/Gun/FirePoint");
hp = transform.Find("HP");
bulletPrefab = (GameObject) Resources.Load("Prefabs/Bullet");
}
private void Update () {
fireWaitTime += Time.deltaTime;
LookAtTarget();
float angle = Vector3.Angle(target.position - top.position, top.forward);
if (LookAtTarget()) {
Fire();
}
HPLookAtCamera();
}
private bool LookAtTarget() {
Vector3 dir = target.position - top.position;
float angle = Vector3.Angle(dir, top.forward);
if (angle > 5) {
int axis = Vector3.Dot(Vector3.Cross(dir, top.forward), Vector3.up) > 0 ? -1 : 1;
GetComponent<Rigidbody>().angularVelocity = axis * Vector3.up * rotateSpeed;
return false;
}
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
return true;
}
private void HPLookAtCamera() {
Vector3 cameraPos = Camera.main.transform.position;
Vector3 target = new Vector3(cameraPos.x, hp.position.y, cameraPos.z);
hp.LookAt(target);
}
private void Fire() {
if (fireWaitTime > bulletCoolTime) {
BulletInfo bulletInfo = new BulletInfo("EnemyBullet", Color.yellow, top.forward, 5f, 10f);
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity); // Create shells from presets
bullet.AddComponent<BulletController>().SetBulletInfo(bulletInfo);
fireWaitTime = 0;
}
}
}
explain : EnemyController The script component is hung on Enemy On the object of the game .
4)BulletController
BulletController.cs
using UnityEngine;
using UnityEngine.UI;
public class BulletController : MonoBehaviour {
private BulletInfo bulletInfo; // Shell information
private volatile bool isDying = false;
private void Start () {
gameObject.name = bulletInfo.name;
GetComponent<MeshRenderer>().material.color = bulletInfo.color;
float lifeTime = bulletInfo.fireRange / bulletInfo.speed; // Survival time
Destroy(gameObject, lifeTime);
}
private void Update () {
transform.GetComponent<Rigidbody>().velocity = bulletInfo.flyDir * bulletInfo.speed;
}
private void OnCollisionEnter(Collision other) {
if (isDying) {
return;
}
if (IsHitEnemy(gameObject.name, other.gameObject.name)) {
other.transform.Find("HP/Health").GetComponent<Image>().fillAmount -= 0.1f;
isDying = true;
Destroy(gameObject, 0.1f);
} else if (IsHitPlayer(gameObject.name, other.gameObject.name)) {
GameObject.Find("PlayerHP/Panel/Health").GetComponent<Image>().fillAmount -= 0.1f;
isDying = true;
Destroy(gameObject, 0.1f);
}
}
public void SetBulletInfo(BulletInfo bulletInfo) {
this.bulletInfo = bulletInfo;
}
private bool IsHitEnemy(string name, string otherName) { // Shoot the enemy
return name.Equals("PlayerBullet") && otherName.Equals("Enemy");
}
private bool IsHitPlayer(string name, string otherName) { // Shoot players
return name.Equals("EnemyBullet") && otherName.Equals("Player");
}
}
explain : BulletController The script component is hung on Bullet On the object of the game ( Dynamic addition in the code ).
5)BulletInfo
BulletInfo.cs
using UnityEngine;
public class BulletInfo {
public string name; // Shell name
public Color color; // Shell color
public Vector3 flyDir; // The direction in which the shell flew
public float speed; // Projectile speed
public float fireRange; // Shell range
public BulletInfo(string name, Color color, Vector3 flyDir, float speed, float fireRange) {
this.name = name;
this.color = color;
this.flyDir = flyDir;
this.speed = speed;
this.fireRange = fireRange;
}
}
4 Running effect
边栏推荐
- Is it safe for Huatai Securities to open an account online, and can VIP accounts be handled
- Halcon series (2): hyperboxes
- Why does the servlet of POM in the web rely on scope as provided
- Carbon language [Chinese introductory course]
- 数据万象内容审核 — 共建安全互联网,专项开展“清朗”直播整治行动
- 分支合并
- Etcdv3 practice · common operation model encapsulation and detailed implementation
- How to debug efficiently (also known as how to solve problems efficiently)
- 华泰证券开户安全性好吗?手续费可以做到万一吗?
- How to use document tools for API management?
猜你喜欢
mysql
How to carry out the anti disclosure work of enterprise source code
2022.7.21 特殊矩阵压缩
cs224w(图机器学习)2021冬季课程学习笔记4
What is a video content recommendation engine?
C # implement setting expiration time for PDF documents
BERTopic
视频提取关键帧工具类KeyFramesExtractUtils.py,动态支持三种取帧方式,关键参数可配置,代码经过优化处理,效果和性能更好。
Delivery practice of private PAAS platform based on cloud native
2022 latest Hubei construction eight members (Mechanics) simulated examination question bank and answers
随机推荐
Servlet优化
Dynamically add and modify the appender of logback (to dynamically adjust the log level and appender parameters)
Summary of five methods of window function
华泰证券网上开户安全吗,VIP账户也可以办理吗
Pango logos dual boot
GL_TRIANGLE_FAN和GL_TRIANGLE_STRIP
2022 latest Hubei construction eight members (Mechanics) simulated examination question bank and answers
Response redirection
2022 Hangdian multi school first personal problem solving (abcdihk)
Halcon知识:用分箱实现OCR分类器
第十六篇,STM32中的ADC模数转换,CAD数模转换和DMA直接内存访问
The most complete summary of MySQL data types in history - (first)
工控行业主机加固为什么要做
企业源代码防泄密工作该如何开展
Urlparrern configuration
转:所有领导者都必须掌握“时机法则”
Basic operation introduction of mongodb, creation and deletion of database / table, and data query
易方达基金上买基金安全吗,我要做基金定投
Why does the servlet of POM in the web rely on scope as provided
计网--应用层