当前位置: 首页 > news >正文

unity3d—demo(2d人物左右移动发射子弹)

目录

人物代码示例:

子弹代码示例:

总结上面代码:

注意点:


人物代码示例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class PlayerTiao : MonoBehaviour
{public float moveSpeed = 10f;private float h;private SpriteRenderer sr;void Start(){sr = this.GetComponent<SpriteRenderer>();}void Update(){h = Input.GetAxis("Horizontal");this.transform.Translate(moveSpeed * Time.deltaTime * Vector3.right *  h);if(h < 0){sr.flipX = true;}else if(h > 0){sr.flipX = false;}if(Input.GetKeyDown(KeyCode.Space)){GameObject obj = Instantiate(Resources.Load<GameObject>("BulletObj"),this.transform.position + new Vector3(sr.flipX ? -0.3f : 0.3f,0.5f,0),Quaternion.identity);obj.GetComponent<Bullet>().ChangeDir(sr.flipX ? Vector3.left : Vector3.right);}}
}

子弹代码示例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Bullet : MonoBehaviour
{public float moveSpeed = 5f;private Vector3 nowDir;void Start(){Destroy(this.gameObject, 3f);}public void ChangeDir(Vector3 dir){nowDir = dir;}void Update(){this.transform.Translate(moveSpeed * Time.deltaTime * nowDir);}
}

总结上面代码:

this.transform.Translate(moveSpeed * Time.deltaTime * nowDir);   transform是属性 获取Transform组件  Translate是Transfor组件方法函数  

预设体 是 GameObject 类型

注意点:

http://www.lryc.cn/news/501658.html

相关文章:

  • 【ETCD】【源码阅读】 深入解析 raftNode.start`函数:Raft 核心启动逻辑剖析
  • Robust Depth Enhancement via Polarization Prompt Fusion Tuning
  • NEFTune,SFT训练阶段给Embedding加噪音
  • uniapp -- 实现页面滚动触底加载数据
  • L22.【LeetCode笔记】相交链表(新版)
  • 智能时代网络空间认知安全新观察
  • 游戏如何应对模拟器作弊
  • c++ 判断一个 IP 地址(可能是 IPv6 或 IPv4)是否属于特定范围
  • 计算机视觉——相机标定(Camera Calibration)
  • 【qt环境配置】windows下的qt与vs工具集安装\版本对应关系
  • GitHub使用
  • 元宇宙时代的社交平台:Facebook的愿景与实践
  • vue2中各种钩子函数的总结以及使用场景
  • 软件架构:从传统单体到现代微服务的技术演变
  • git新建远程分支后,无法切换
  • 【SpringBoot】31 Session + Redis 实战
  • 在Windows环境下的rknn-toolkit环境搭建
  • Facebook广告突然无消耗?原因解析与解决方案。
  • Rabbitmq 镜像队列
  • TensorBoard
  • 运维实战:K8s 上的 Doris 高可用集群最佳实践
  • 2024.12.5——攻防世界Training-WWW-Robots攻防世界baby_web
  • 当 Nginx 出现连接超时问题,如何排查?
  • vue2 项目中实现动态代理,服务器上通过nginx部署 实现动态代理
  • 基于SpringBoot+Vue的民宿山庄农家乐管理系统
  • 【数据分享】1901-2023年我国省市县三级逐年最低气温数据(Shp/Excel格式)
  • 后端API接口设计标准(Java)
  • 网络安全法 -网络信息安全
  • matlab figure函数 single 数据类型
  • endroid/qr-code生成二维码,中文乱码的解决方案