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

CocosCreator 3.x 实现角色移动与加载时动态屏幕边缘检测

效果

请添加图片描述

思路

  1. 通过cc.view全局单例 View 对象获取屏幕尺寸
  2. 加载时根据屏幕尺寸动态计算上下左右边缘

代码实现

import { _decorator, Component, EventTouch, Input, input, Node, view } from 'cc';
const { ccclass, property } = _decorator;/*** 玩家控制脚本*/
@ccclass('Player')
export class Player extends Component {/** 左边界 */private leftBound: number;/** 右边界 */private rightBound: number;/** 上边界 */private topBound: number;/** 下边界 */private bottomBound: number;protected onLoad(): void {// 初始化边界this.initBound();// 监听触摸移动事件input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);}/*** 初始化边界*/initBound() {/** 获取背景尺寸 */let height = view.getVisibleSize().height;let width = view.getVisibleSize().width;/** 设置边界 */this.leftBound = -width / 2;this.rightBound = width / 2;this.bottomBound = -height / 2;this.topBound = height / 2;}protected onDestroy(): void {// 取消监听触摸移动事件input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);}/*** 触摸移动回调* @param event 触摸事件*/onTouchMove(event: EventTouch) {// 计算出移动位置let posX = this.node.getPosition().x + event.getDeltaX();let posY = this.node.getPosition().y + event.getDeltaY();// 水平边界限制posX = Math.max(this.leftBound, posX);posX = Math.min(this.rightBound, posX);// 垂直边界限制posY = Math.max(this.bottomBound, posY);posY = Math.min(this.topBound, posY);// 更新位置this.node.setPosition(posX, posY);}
}

http://www.mrgr.cn/news/33212.html

相关文章:

  • 嵌入式 开发技巧和经验分享
  • PHP如何从字符串中删除转义字符
  • 【C++】仿函数
  • 未来视界,触手可及:bigmp4 引领 AI 视频处理新革命
  • 教师师生关系研判:基于信任建立、课堂管理、学生心理支持、沟通技巧与反馈改进的综合分析
  • 嵌入式常用GUI介绍
  • 用Python实现时间序列模型实战——Day 30: 学习总结与未来规划
  • NXP实战笔记(十六):NXP 32K3xx系列单片机有关OTA升级的思考
  • 某省公共资源交易电子平台爬虫逆向
  • 2024年研赛 C、D、F三题论文首发+部分代码分享
  • CSS3 多媒体查询
  • 【保奖思路】2024年华为杯研赛B题完整代码建模过程(后续会更新)
  • 医院伤员消费点餐限制———未来之窗行业应用跨平台架构
  • UE Asset Batch Duplication插件
  • 用java实现一个多表关联
  • CTC loss 博客转载
  • Linux基础命令以及常识
  • 【C++】STL----deque
  • 扎克伯格的未来愿景 用智能眼镜引领数字社交互动新时代
  • python使用笔记