当前位置:网站首页>[unity3d] rocker
[unity3d] rocker
2022-07-26 18:04:00 【little_ fat_ sheep】
1 Demand fulfillment
1) Demand fulfillment
- Drag the joystick ball with the mouse to control the movement of the tank ;
- Up, down, left and right buttons can also control tank movement , And the rocker ball also moves synchronously ;
- Right mouse button sliding , Control the tank steering ;
- The position of the camera above the back of the player , Always follow the player , Look directly in front of the player ;
- Click the left mouse button to control the tank to launch shells .
2) It's about the technology stack
- Transform Components
- human-computer interaction Input
- Rigid body components Rigidbody
- The camera follows
- Canvas Rendering mode and anchor
- UGUI And Image
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 .
2. 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. rocker RectTransform Component parameters
| Name | Type | Width/Height | Pos | Anchors |
|---|---|---|---|---|
| Stick | Canvas | —— | —— | —— |
| Background | Image | (100, 100) | (75, 75, 0) | (0, 0), (0, 0) |
| Ball | Image | (40, 40) | (75, 75, 0) | (0, 0), (0, 0) |
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 StickController stick; // Rocker controls
private float tankMoveSpeed = 4f; // Tank moving speed
private float tankRotateSpeed = 2f; // The turning speed of the tank
private Vector3 predownMousePoint; // Position when the mouse is pressed
private Vector3 currMousePoint; // Current mouse position
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");
stick = GameObject.Find("Stick/Ball").GetComponent<StickController>();
}
private void Update() {
Move();
Rotate();
Fire();
}
private void Move() { // Tank movement
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
Move(hor, ver);
}
public void Move(float hor, float ver) { // Tank movement
if (Mathf.Abs(hor) > float.Epsilon || Mathf.Abs(ver) > float.Epsilon) {
Vector3 vec = transform.forward * ver + transform.right * hor;
GetComponent<Rigidbody>().velocity = vec * tankMoveSpeed;
// stick.UpdateStick(new Vector3(hor, 0, ver));
Vector3 dire = new Vector3(hor, ver, 0);
dire = dire.normalized * Mathf.Min(dire.magnitude, 1);
stick.UpdateStick(dire);
}
}
private void Rotate() { // The tank rotates
if (Input.GetMouseButtonDown(1)) {
predownMousePoint = Input.mousePosition;
} else if (Input.GetMouseButton(1)) {
currMousePoint = Input.mousePosition;
Vector3 vec = currMousePoint - predownMousePoint;
GetComponent<Rigidbody>().angularVelocity = Vector3.up * tankRotateSpeed * vec.x;
predownMousePoint = currMousePoint;
}
}
private void Fire() { // The tank fired
fireWaitTime += Time.deltaTime;
if (Input.GetMouseButtonDown(0) && !IsMouseInUIArea() || Input.GetKeyDown(KeyCode.Space)) {
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;
}
}
}
private bool IsMouseInUIArea() { // Mouse in UI Control area
Vector3 pos = Input.mousePosition;
return pos.x < 150 && pos.y < 150;
}
}explain : PlayerController The script component is hung on Player On the object of the game .
3)StickController
StickController.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class StickController : MonoBehaviour, IDragHandler, IEndDragHandler {
private Vector3 originPos; // Position when the mouse starts dragging
private Vector3 currPos; // Current mouse position
private float radius; // Remote rod radius
private PlayerController player; // Player controller
private Vector3 dire = Vector3.zero; // The orientation of the rocker ball
private void Start () {
originPos = transform.position;
radius = 50;
player = GameObject.Find("Player").GetComponent<PlayerController>();
}
private void Update () {
player.Move(dire.x, dire.y);
}
public void OnDrag(PointerEventData eventData) {
Vector3 vec = Input.mousePosition - originPos;
dire = vec.normalized * Mathf.Min(vec.magnitude / radius, 1);
UpdateStick(dire);
}
public void OnEndDrag(PointerEventData eventData) {
transform.position = originPos;
dire = Vector3.zero;
}
public void UpdateStick(Vector3 dire) { // Update the rocker position
transform.position = originPos + dire * radius;
}
}explain : StickController The script component is hung on Ball 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 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;
}
public void SetBulletInfo(BulletInfo bulletInfo) {
this.bulletInfo = bulletInfo;
}
}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

边栏推荐
- 跨站点请求伪造(CSRF)
- SSH based online mall
- Diagram of seven connection modes of MySQL
- 【云原生】 iVX 低代码开发 引入腾讯地图并在线预览
- JS function scope variables declare that the variables that promote the scope chain without VaR are global variables
- Vector CANoe Menu Plugin拓展入门
- 6、 Common commands of ROS (I): rosnode, rostopic, rosmsg
- 常用api
- Detailed explanation of openwrt's feeds.conf.default
- Cross Site Request Forgery (CSRF)
猜你喜欢

How to assemble a registry?

【集训Day2】Torchbearer

Machine learning by Li Hongyi 2. Regression

Relative path and absolute path

236. The nearest common ancestor of a binary tree
![[training Day1] Dwaves line up](/img/ee/9c83f664cf516f516e906b78146efb.png)
[training Day1] Dwaves line up

Several ways to resolve hash conflicts
![[day3] reconstruction of roads](/img/52/cc8b81bccbf4aa02ec82fedfb49d19.png)
[day3] reconstruction of roads

Hardware development and market industry

浅析接口测试
随机推荐
PMP考试详解,新考纲有什么变化?
DTS is equipped with a new self-developed kernel, which breaks through the key technology of the three center architecture of the two places Tencent cloud database
Deep learning experiment: softmax realizes handwritten digit recognition
【元宇宙欧米说】剖析 Web3 风险挑战,构筑 Web3 生态安全
相对路径与绝对路径
即刻报名|飞桨黑客马拉松第三期盛夏登场,等你挑战
8、 Topic communication: topic substitution and monitoring
Centos安装docker以及mysql和redis环境
Spark统一内存划分
.net CLR GC dynamic loading transient heap threshold calculation and threshold excess calculation
长征证券开户安全吗?
7月30号PMP考试延期后我们应该做什么?
ICML 2022(第四篇)|| 图分层对齐图核实现图匹配
ACL experiment demonstration (Huawei router device configuration)
What is the PMP exam outline in 2022?
DTS搭载全新自研内核,突破两地三中心架构的关键技术|腾讯云数据库
【集训Day2】Torchbearer
JS function scope variables declare that the variables that promote the scope chain without VaR are global variables
【集训Day2】cinema ticket
[metauniverse OMI theory] analyze Web3 risk challenges and build Web3 ecological security