栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

Cocos Creator

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Cocos Creator

    // 刷新消息
    setMessage(name: string, content: string){
    // 从子节点中拿到cc.Label组件
        this.node.children[0].getComponent(cc.Label).string = name;
        this.node.children[1].getComponent(cc.Label).string = content;
    }
节点常用属性方法
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        // 获得子节点
        // this.node.children[0];
        // this.node.getChildByName("abc");
        // cc.find("Canvas/Main Camera")
        // 获得父节点
        // this.node.getParent();
        // 设置父节点
        // this.node.setParent(ddd);
        // 移除所有子节点
        // this.node.removeAllChildren();
        // 移除某个子节点
        // this.node.removeChild(ddd);
        // 从父节点中移除
        // this.node.removeFromParent();

        // 访问位置
        // this.node.x
        // this.node.y
        // this.node.setPosition(3,4);
        // this.node.setPosition(cc.v2(3,4));
        // 旋转
        // this.node.rotation
        // 缩放
        // this.node.scale
        // 锚点
        // this.node.anchorX
        // this.node.color = cc.Color.RED;

        // 节点开关
        // this.node.active = false;
        // 组件开关
        // this.enabled = false;

        // 获取组件
        // let sprit = this.getComponent(cc.Sprite);
        // 精灵组件开关
        // sprite.enabled
        // 从子物体里面获取精灵组件     如果获取失败,则返回null
        this.getComponentInChildren(cc.Sprite);
    }

    // 每帧调用
    update (dt) {
    }
}
预设体的使用
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    // 预设体
    @property(cc.Prefab)
    pre: cc.Prefab = null;

    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        // // 创建节点
        // let node = new cc.Node("new");
        // // 添加组件
        // node.addComponent(cc.Sprite);

        // 实例化预设体    最后返回是一个节点
        let node = cc.instantiate(this.pre);
        // 设置父节点
        node.setParent(this.node);
    }

    // 每帧调用
    update (dt) {
    }
}
动态加载
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';


    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        let self = this;
        //  第一个位置可填网址http://www.baidu.com/1.png    第二个位置可填写指定类型,此处为图片
        // cc.loader.loadRes("test/白", cc.SpriteFrame, function(err, sp){
        //     self.getComponent(cc.Sprite).spriteFrame = sp;
        // });

        // 图集加载
        // 这前面还可以写成 cc.resources.load
        cc.loader.loadRes("test/1", cc.SpriteAtlas, function(err, atlas: cc.SpriteAtlas){
            self.getComponent(cc.Sprite).spriteFrame = atlas.getSpriteFrame("bg_day");
        });
    }

    // 每帧调用
    update (dt) {
    }
}
场景管理
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';


    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        // 加载第二个场景

        // 小资源加载法
        // cc.director.loadScene("game2", function(){
        //     // 当前已经记载到新的场景里了
        // });

        // 大型游戏加载
        // 预加载
        // cc.director.preloadScene("game2",function(){
        //     // 这个场景加载到内存了,但是还没有用
        //     cc.director.loadScene("game2");
        // });

        // 添加常驻节点
        cc.game.addPersistRootNode(this.node);
        cc.game.removePersistRootNode(this.node);
    }

    // 每帧调用
    update (dt) {
    }
}
键鼠事件
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';


    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        // 鼠标事件
        this.node.on(cc.Node.EventType.MOUSE_DOWN,function(event){
            console.debug("鼠标按下了,位置在:"+ event.getLocation());
        });

        this.node.on(cc.Node.EventType.MOUSE_DOWN,function(event){
            if(event.getButton() == cc.Event.EventMouse.BUTTON_LEFT){
                console.debug("左键");
            }
            if(event.getButton() == cc.Event.EventMouse.BUTTON_RIGHT){
                console.debug("右键");
            }
        });

        this.node.on(cc.Node.EventType.MOUSE_ENTER,function(event){
            console.debug("鼠标移进来了,位置在:"+ event.getLocation());
        });

        this.node.on(cc.Node.EventType.MOUSE_MOVE,function(event){
            console.debug("鼠标在移动,位置在:"+ event.getLocation());
        });

        this.node.on(cc.Node.EventType.MOUSE_LEAVE,function(event){
            console.debug("鼠标离开了,位置在:"+ event.getLocation());
        });

        this.node.on(cc.Node.EventType.MOUSE_UP,function(event){
            console.debug("鼠标松开了,位置在:"+ event.getLocation());
        });

        this.node.on(cc.Node.EventType.MOUSE_WHEEL,function(event){
            console.debug("滚轮动了,位置在:"+ event.getLocation());
        });

        // 键盘事件
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, function(event){
            if(event.keyCode == cc.macro.KEY.w){
                console.debug("w");
            }
            if(event.keyCode == cc.macro.KEY.a){
                console.debug("a");
            }
        })
        
    }

    // 每帧调用
    update (dt) {
    }
}
触摸与自定义事件
const {ccclass, property} = cc._decorator;

@ccclass
export default class Text extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';


    // LIFE-CYCLE CALLBACKS:

    // 初始化调用
    start () {
        // 键盘事件
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, function(event){
            if(event.keyCode == cc.macro.KEY.w){
                console.debug("w");
            }
            if(event.keyCode == cc.macro.KEY.a){
                console.debug("a");
            }
        });
        // 触摸事件
        let self = this;
        this.node.on(cc.Node.EventType.TOUCH_START, function(event){
            // 区分手指
            // console.debug("触摸的是第几个手指:"+ event.getID());
            // 得到触摸的位置
            // console.debug("触摸:"+ event.getLocation());
            // 第一个自定义方法
            // self.node.emit("myevent1");
            // 第二个     第二个参数表示是否冒泡
            // self.node.dispatchEvent(new cc.Event.EventCustom("myevent1", true));
        });

        // 监听自定义事件
        this.node.on("myevent1", function(event){
            console.debug("自定义事件");
        })

    }

    // 每帧调用
    update (dt) {
    }
}
碰撞检测
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        // 记得先添加碰撞组件
        // 碰撞检测
        cc.director.getCollisionManager().enabled = true;
    }

    // 产生碰撞会调用一次
    onCollisionEnter(other){
        console.debug("碰撞发生" + other.tag);
    }

    onCollisionStay(other){
        console.debug("碰撞持续");
    }

    onCollisionExit(other){
        console.debug("碰撞结束");
    }
}
音频播放
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {


    start () {
        // 一、组件的播放方式
        // 得到一个组件,类型是audiosource
        let player: cc.AudioSource = this.getComponent(cc.AudioSource);
        // 加载音频
        cc.loader.loadRes("飞羽",cc.AudioClip, (res,clip) => {
            // 赋值音频
            player.clip = clip;
            // 播放
            player.play();
            // 是否正在播放
            // player.isPlaying

            // 暂停
            // player.pause();

            // 恢复
            // player.resume();

            // 停止
            // player.stop();

            // 是否循环播放
            player.loop = true;
            // 音量
            player.volume = 1;
        });

        // 二、非组件方式
        // 加载音频
        cc.loader.loadRes("飞羽",cc.AudioClip, (res,clip)=>{
            // 播放  播放引擎     参数:音频片段,是否循环
            let audioId: number = cc.audioEngine.playMusic(clip, true);
            // 是否正在播放
            // cc.audioEngine.isMusicPlaying();

            // 暂停
            cc.audioEngine.pause(audioId);
            cc.audioEngine.pauseMusic();

            // 恢复
            cc.audioEngine.resume(audioId);

            // 停止
            cc.audioEngine.stop(audioId);

            // 循环
            cc.audioEngine.setLoop(audioId,true);

            // 声音大小  0到1
            cc.audioEngine.setVolume(audioId,1);
        });
    }

    // update (dt) {}
}
物理系统(含物理碰撞)

物理系统必须在onload里面开启

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    onLoad () {
        cc.director.getPhysicsManager().enabled = true;
    }

    start () {
        // 获取刚体
        let rbody = this.getComponent(cc.RigidBody);
        // 给一个力    参数:水平和垂直给多大的力,施力的点在哪,是否运用
        // rbody.applyForce(cc.v2(1000,0), cc.v2(0,0), true);
        // 给物体中心施力
        // rbody.applyForceToCenter(cc.v2(5000,0),true);

        // 速度(每秒像素)
        rbody.linearVelocity = cc.v2(400,0);
    }

    // 开始碰撞    contact碰撞的一个类
    onBeginContact(contact, self, other){
        // 得到碰撞点   返回的是一个数组
        let points = contact.getWorldManifold().points;
        // 法线
        let normal = contact.getWorldManifold().normal;
        console.debug("发生碰撞" + points[0] + normal);
    }

    // 结束碰撞
    onEndContact(contact, self, other){

    }

    update (dt) {}
}
射线
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    onLoad () {
        cc.director.getPhysicsManager().enabled = true;
        // 打出一条射线    this.node.getPosition()得到自己的位置     cc.v2(this.node.x, this.node.y + 100)向上打一条射线     
        let results = cc.director.getPhysicsManager().rayCast(this.node.getPosition(),cc.v2(this.node.x, this.node.y + 100),cc.RayCastType.Closest);
        for(let i = 0;i < results.length; i++){
            let res = results[i];
            // 射线碰到的碰撞器
            // res.collider
            // 碰到的点
            // res.point
            // 碰到的法线
            // res.normal
        }
    }

    start () {
        // 获取刚体
        let rbody = this.getComponent(cc.RigidBody);
        // 给一个力    参数:水平和垂直给多大的力,施力的点在哪,是否运用
        // rbody.applyForce(cc.v2(1000,0), cc.v2(0,0), true);
        // 给物体中心施力
        // rbody.applyForceToCenter(cc.v2(5000,0),true);

        // 速度(每秒像素)
        rbody.linearVelocity = cc.v2(400,0);
    }

    // 开始碰撞    contact碰撞的一个类
    onBeginContact(contact, self, other){
        // 得到碰撞点   返回的是一个数组
        let points = contact.getWorldManifold().points;
        // 法线
        let normal = contact.getWorldManifold().normal;
        console.debug("发生碰撞" + points[0] + normal);
    }

    // 结束碰撞
    onEndContact(contact, self, other){
        console.debug("结束碰撞");
    }

    update (dt) {}
}
射线练习
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    onLoad () {
        cc.director.getPhysicsManager().enabled = true;
        // 打出一条射线    this.node.getPosition()得到自己的位置     cc.v2(this.node.x, this.node.y + 100)向上打一条射线     
        let results = cc.director.getPhysicsManager().rayCast(this.node.getPosition(),cc.v2(this.node.x, this.node.y + 100),cc.RayCastType.Closest);
        for(let i = 0;i < results.length; i++){
            let res = results[i];
            // 射线碰到的碰撞器
            // res.collider
            // 碰到的点
            // res.point
            // 碰到的法线
            // res.normal
        }
    }

    start () {
        // 获取刚体
        let rbody = this.getComponent(cc.RigidBody);
        // 给一个力    参数:水平和垂直给多大的力,施力的点在哪,是否运用
        // rbody.applyForce(cc.v2(1000,0), cc.v2(0,0), true);
        // 给物体中心施力
        // rbody.applyForceToCenter(cc.v2(5000,0),true);

        // 速度(每秒像素)
        rbody.linearVelocity = cc.v2(400,0);
    }

    // 开始碰撞    contact碰撞的一个类
    onBeginContact(contact, self, other){
        // 得到碰撞点   返回的是一个数组
        let points = contact.getWorldManifold().points;
        // 法线
        let normal = contact.getWorldManifold().normal;
        console.debug("发生碰撞" + points[0] + normal);
    }

    // 结束碰撞
    onEndContact(contact, self, other){
        console.debug("结束碰撞");
    }

    update (dt) {}
}
动作系统
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    start () {
        // 动作
        // 移动  2s后到(200,200)的位置   绝对位置
        let action = cc.moveTo(2, 200, 200);
        // 相对位置   以自己为原点
        action = cc.moveBy(2, 200, 200);
        // 旋转
        action = cc.rotateTo(2, 100);
        // 缩放
        action = cc.scaleTo(2, 1.5);
        // 跳跃    2s后跳到(200,0)的位置,跳的高度为100,跳1次
        action = cc.jumpBy(2, 200, 0, 100, 1);
        // 闪烁     3s闪烁5次
        action = cc.blink(3, 5);
        // 淡出
        action = cc.fadeOut(3);
        // 淡入
        action = cc.fadeIn(3);
        // 渐变 0~255    3s变到透明度为100
        action = cc.fadeTo(3, 100);
        // 颜色     3s后变到rgb值为(100,30,100)的颜色
        action = cc.tintTo(3, 100,  30, 100);


        // 执行动作
        this.node.runAction(action);
        // 停止动作
        // this.node.stopAction(action);
        // this.node.stopAllActions();
        // 通过Tag值停止动作
        // action.setTag(3);
        // this.node.stopActionByTag(3);

        // 暂停所有动作
        // this.node.pauseAllActions();
        // 恢复所有动作
        // this.node.resumeAllActions();
    }

    // update (dt) {}
}
容器动作
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    start () {
        // 动作
        // 立刻显示
        let action = cc.show();
        // 立刻隐藏  
        action = cc.hide();
        // 切换显示隐藏
        action = cc.toggleVisibility();
        // 翻转
        action = cc.flipX(true);
        action = cc.flipY(true);
        // 回调动作
        action = cc.callFunc(() => {

        });

        // 1s 淡出
        action = cc.fadeOut(1);
        let action2 = cc.fadeIn(1);
        // 队列/序列 动作     cc.delayTime(1)延时1s
        let seq = cc.sequence(action, action2, cc.delayTime(1), cc.callFunc(() => {

        }));
        // 重复动作    重复三次
        let repeat = cc.repeat(seq, 3);
        // 一直重复
        repeat = cc.repeatForever(seq);

        // 并列动作
        let move = cc.moveTo(3,500,500);
        let color = cc.tintTo(3, 100, 100, 20);
        let spawn = cc.spawn(move,color);

        this.node.runAction(spawn);

    }

    update (dt) {

    }
}
对话框练习

人物

const {ccclass, property} = cc._decorator;

@ccclass
export default class Person extends cc.Component {


    start () {

    }

    update (dt) {}

    // 设置表情
    setImage(face: string, mouth: string){
        // 加载素材
        cc.loader.loadRes(face, cc.SpriteFrame, (err,sp) => {
            this.node.children[0].getComponent(cc.Sprite).spriteFrame = sp;
        });
        cc.loader.loadRes(mouth, cc.SpriteFrame, (err,sp) => {
            this.node.children[1].getComponent(cc.Sprite).spriteFrame = sp;
        });
    }
}

对话

const {ccclass, property} = cc._decorator;

@ccclass
export default class MsgControl extends cc.Component {

    start () {

    }

    update (dt) {}

    // 刷新消息
    setMessage(name: string, content: string){
        this.node.children[0].getComponent(cc.Label).string = name;
        this.node.children[1].getComponent(cc.Label).string = content;
    }
}

bg总控制(父节点

import MsgControl from "./MsgControl";

const {ccclass, property} = cc._decorator;

class Message{
    name: string;
    content: string;
    // face: string;
    // mouth:string;

    constructor(name: string, content: string){   // face: string, mouth: string
        this.name = name;
        this.content = content;
        // this.face = face;
        // this.mouth = mouth;
    }
}

@ccclass
export default class BgControl extends cc.Component {
    // 人物和消息的控制器
    // @property(Person)
    // person: Person = null;
    @property(MsgControl)
    msgControl: MsgControl = null;

    // 消息数组
    msgs: Message[] = null;
    // 当前是第几条消息
    index: number = 0;


    start () {
        // 初始化数组
        this.msgs = [
            new Message("同学1","今天天气不错"),
            new Message("同学1","就是有点太阳"),
            new Message("同学1","打伞就好了")
        ];
        // 鼠标点击对话
        this.node.on(cc.Node.EventType.MOUSE_DOWN,(event) =>{
            if(this.index <= this.msgs.length){
                // 如果对话面板没显示,显示
                if(this.msgControl.node.active == false){
                    this.msgControl.node.active = true;
                }
                // 读消息
                let message = this.msgs[this.index++];
                // 显示消息
                // this.Person.setImage(message.face, message.mouth);
                this.msgControl.setMessage(message.name, message.content);
            }
        });
    }

    // update (dt) {}
}
数据存储
const {ccclass, property} = cc._decorator;

@ccclass
export default class DataTest extends cc.Component {
    start () {
        // 储存数据(键值对方式)
        // cc.sys.localStorage.setItem("name","名字");
        // 获取数据
        // let name  = cc.sys.localStorage.getItem("name");
        // console.debug(name);
        // 移除数据
        // cc.sys.localStorage.removeItem("name");
        // 清空
        // cc.sys.localStorage.clear();
    }

    update (dt) {}
}
Json数据
const {ccclass, property} = cc._decorator;

class Person{
    id:number;
    name: string;
    wugong: string[];
    // ...
}

@ccclass
export default class NewClass extends cc.Component {
    start () {
        

        let person: Person = new Person();
        person.id = 10;
        person.name = "李逍遥";
        person.wugong = ["降龙十八掌", "孤独九剑"];

        // 把对象 ->  字符串
        
        //  对象 -> json   序列化
        let json = JSON.stringify(person);
        // console.debug(json);
        // 存档
        // cc.sys.localStorage.setItem("save1",json);
        // json -> 对象    反序列化
        let person2: Person = Object.assign(new Person(),JSON.parse(json));
        console.debug(person2.name);

    }

    update (dt) {

    }
}
数据格式
        // person[] -> 字符串
        // json
        

        // xml
            
网络请求
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    start () {
        // url
        let url = "https://api.kuaidi100.com/";
        // 请求
        let request = cc.loader.getXMLHttpRequest();
        request.open("GET",url,true);   // 最后一个参数表示是否异步
        request.onreadystatechange = () =>{
            // 请求状态改变
            // 请求结束后,获取信息
            if(request.readyState == 4 && request.status == 200){
                console.debug("请求完成");
                console.debug(request.responseText);
            }
        };
        // 开始请求
        request.send();
    }

    update (dt) {}
}
自定义 Animation动画组件
const {ccclass, property} = cc._decorator;

@ccclass
export default class MyAnimation extends cc.Component {
    // 每秒播放速度
    @property
    speed: number = 0.1;
    // 播放帧数组
    @property([cc.SpriteFrame])
    sprites: cc.SpriteFrame[] = [];
    // 是否播放动画
    @property
    isPlay: boolean = false;
    // 当前播放帧
    index: number = 0;
    // 计时器
    timer: number = 0;


    start () {
    }

    play(){
        this.isPlay = true;
    }

    stop(){
        this.isPlay = false;
    }

    update (dt) {
        if(this.isPlay){
            // 播放动画
            // 计时器增加
            this.timer += dt;
            if(this.timer > this.speed){
                this.timer = 0;
                // 切换帧   0 1 2循环
                this.index++;
                if(this.index >= this.sprites.length){
                    this.index = 0;
                }
                // 更换帧图片
                this.getComponent(cc.Sprite).spriteFrame = this.sprites[this.index];
            }
        }
    }
}

控制播放:

import MyAnimation from "./MyAnimation";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    start () {
        this.getComponent(MyAnimation).play();
    }

    // update (dt) {}
}
node.js服务端

 服务器    js文件:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// 在某个端口开始监听客户端连接   此处为3000
http.listen(3000,function(){
    console.log("server listen on 3000");
});

// 监听有客户端连接    这里的socket是真正与之连接的套接字
io.on('connection', function(socket){
    // 发送消息
    // socket.emit('message','连接成功了');
    // 监听客户端发来的消息     data就是客户端发来的消息
    console.log("客户端连接");
    socket.on('message',function(data){
        console.log("客户端发来消息:"+ data);
        // 给客户端发消息
        socket.emit('message','world');
    });
});
Socket.io客户端

客户端  ts文件:

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
    scoket: Socket = null;
    start () {
        // 连接服务器
        this.socket = io.connect("http://localhost:3000");
        // 判断是否连接成功
        this.scoket.on('connect', (data) =>{
            console.debug("连接成功了");
            // 给服务端发消息
            this.scoket.emit("message","hello");

            // 客户端接收消息
            this.scoket.on('message',(data)=>{
                console.debug(data);
            });
        });

        // 判断是否断开
        this.scoket.on('disconnect',(data)=>{

        });
    }

    update (dt) {}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901878.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号