project creation
1. Create a unity project, select 2D > Project Name Tank > Create
2. Open Assets
3. Import the GameResource.unitypackage resource file
resource handling
1. Import the tank in the resource into the Hierarchy, and change the resource size x and y to 3
Import Wall, Steel Wall Barriar, Grass Grass and Heart into Hierarchy
2. Create animation
Select all the pictures in Born, pull in the Hierarchy, change the name to Born, and put the resources generated by the animation into Animation and AnimationController respectively
3. Prefabricated body
Drag the resources into the Effect (animation resource) and Map (non-animation resource) under the prefab folder Prefobs respectively
4. Collision detection
Add collision detection and rigid body for Player
Added collision detection for Barriar, Heart, River, Wall
To prevent the decline of the rigid gravity effect and the rotation of the tank after the collision, set the value as follows, where the space in front of z is selected to lock the z-axis without rotation after the collision, and set the Gravity Scale (gravity) to 0.
5. The tank moves and fires bullets
Create a script and drag it into the component, where the pictures corresponding to the property values of bullets and tanks are in the positions shown in the figure
The direction control of the tank uses four pictures to control the display
bullet according to the method in the script. The direction control of the bullet uses one picture to control the angle according to the third parameter of the picture instantiation method in the script.
Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
//属性值
public float moveSpeed = 3;
private Vector3 bullectEulerAngles;
//引用
public Sprite[] tankSprite; //上 右 下 左
private SpriteRenderer sr;
public GameObject bullectPrefab; //子弹的预制体
private void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Attack();
}
private void FixedUpdate()
{
Move();
}
//坦克的攻击方法
private void Attack()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//子弹产生的角度:当前坦克的角度+子弹应该旋转的角度。
Instantiate(bullectPrefab, transform.position, Quaternion.Euler(transform.eulerAngles+bullectEulerAngles));
}
}
//坦克的移动方法
public void Move()
{
float v = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.up * v * moveSpeed * Time.deltaTime, Space.World);
if (v < 0)
{
sr.sprite = tankSprite[2];
bullectEulerAngles = new Vector3(0, 0, 180);
}
else if (v > 0)
{
sr.sprite = tankSprite[0];
bullectEulerAngles = new Vector3(0, 0, 0);
}
if (v != 0)
{
return;
}
float h = Input.GetAxisRaw("Horizontal");
transform.Translate(Vector3.right * h * moveSpeed * Time.deltaTime, Space.World);
if (h < 0)
{
sr.sprite = tankSprite[3];
bullectEulerAngles = new Vector3(0, 0, 90);
}
else if (h > 0)
{
sr.sprite = tankSprite[1];
bullectEulerAngles = new Vector3(0, 0, -90);
}
}
}