射箭游戏
游戏视频<https://www.bilibili.com/video/av71160101/>
游戏工程文件https://github.com/JennySRH/3DGame/tree/master/ShootTarget
上下左右控制箭移动,空格键发射
靶对象
靶对象共有5环,由5个圆柱体组成,射中最中心的环得分5,射中最外层环得分为1。每个圆柱体都添加了mesh collider
,勾选Convex
,并且勾选了is Trigger
作为触发器。
对于靶对象而言,它需要完成两种行为:
- 作为触发器,感知是否有箭射中其中的某一环。
- 作为model,包含每一环的分数。
Target
上将挂载两个脚本,一个是TargetData
,挂载到每一个环上,用来得到该环的分数;另一个是TargetTrigger
,用来检测哪一个环被触发。
/* TargetData.cs */
public class TargetData : MonoBehaviour
{
// 挂载到Target上的每一环,用来返回该环对应的分数。
public int GetScore()
{
string name = this.gameObject.name;
int score = 6 - (name[0] - '0');
return score;
}
}
/*TargetTrigger.cs*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetTrigger : MonoBehaviour
{
// 当有箭射中某一环后触发
void OnTriggerEnter(Collider arrow_head)
{
//得到箭身
Transform arrow = arrow_head.gameObject.transform.parent;
if (arrow == null)
{
return;
}
if (arrow.tag == "Arrow")
{
arrow_head.gameObject.SetActive(false);
//箭身速度为0
arrow.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
arrow.GetComponent<Rigidbody>().isKinematic = true;
arrow.tag = "Hit";
// 分数控制器
int score = this.gameObject.gameObject.GetComponent<TargetData>().GetScore();
Singleton<ScoreController>.Instance.AddScore(score);
//Debug.Log(score);
}
}
}
然后将所有的圆柱体放到一个空物体上,做成预制。
箭
每一个箭由head
和body
组成,head
装有collider
。
箭挂载了JoyStick
可以通过上下左右来控制方向,如果按下空格键将添加刚体Rigidbody
,然后交由相应的动作控制器进行控制。
/*JoyStick.cs*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JoyStick : MonoBehaviour
{
public float speedX = 1.0F;
public float speedY = 1.0F;
bool flag = true;
// Update is called once per frame
void Update()
{
// 只有在射出前能移动
if(flag)
{
float translationY = Input.GetAxis("Vertical") * speedY;
float translationX = Input.GetAxis("Horizontal") * speedX;
translationY *= Time.deltaTime;
translationX *= Time.deltaTime;
// 限制移动的范围
if (transform.position.x - translationX <