Unity学习——射箭游戏

本文介绍了Unity中射箭游戏的开发过程,包括靶对象、箭、风的设置,以及运动学和动力学控制器的实现。游戏包含上下左右移动、空格发射箭的功能,靶对象有不同的得分环,风力会影响箭的轨迹。此外,还讨论了记分器和场景控制器的实现,并提及了对打飞碟游戏的改进,引入了运动接口和adapter模式。
摘要由CSDN通过智能技术生成

射箭游戏

游戏视频<https://www.bilibili.com/video/av71160101/>
游戏工程文件https://github.com/JennySRH/3DGame/tree/master/ShootTarget
上下左右控制箭移动,空格键发射

靶对象

靶对象共有5环,由5个圆柱体组成,射中最中心的环得分5,射中最外层环得分为1。每个圆柱体都添加了mesh collider,勾选Convex,并且勾选了is Trigger作为触发器。

在这里插入图片描述
在这里插入图片描述
对于靶对象而言,它需要完成两种行为:

  1. 作为触发器,感知是否有箭射中其中的某一环。
  2. 作为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);
        }
    }

}

然后将所有的圆柱体放到一个空物体上,做成预制。

在这里插入图片描述

每一个箭由headbody组成,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 <
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值