cocos中物体跟随触点旋转及缩放

需求一:让被控制物体随着触点移动而进行旋转(计算角色中心到触摸点形成的连线与与y轴正半轴之间的夹角)

function getAngle(px,py,mx,my){//获得人物中心和鼠标坐标连线,与y轴正半轴之间的夹角
        var x = Math.abs(px-mx);
        var y = Math.abs(py-my);
        var z = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
        var cos = y/z;
        var radina = Math.acos(cos);//用反三角函数求弧度
        var angle = Math.floor(180/(Math.PI/radina));//将弧度转换成角度

        if(mx>px&&my>py){//鼠标在第四象限
            angle = 180 - angle;
        }

        if(mx==px&&my>py){//鼠标在y轴负方向上
            angle = 180;
        }

        if(mx>px&&my==py){//鼠标在x轴正方向上
            angle = 90;
        }

        if(mx<px&&my>py){//鼠标在第三象限
            angle = 180+angle;
        }

        if(mx<px&&my==py){//鼠标在x轴负方向
            angle = 270;
        }

        if(mx<px&&my<py){//鼠标在第二象限
            angle = 360 - angle;
        }



            return angle;
    }

node.angle = this.getAngle(px,py,mx,my)
如果在控制物体的脚本中进行touch监听,在touch_move阶段持续(如果只想让物体原地旋转,就不需要在touch_move中不断为物体赋值新的坐标)获得触点与物体中心的连线与y轴正半轴之间的夹角,那么物体就会跟随触点进行以锚点为中心的旋转。

需求二:物体的尺寸随着触点移动而进行缩放

思路:
1、计算touch_start时触点的坐标与物体中心坐标的距离dist1;
2、计算touch_move时触点的坐标与物体中心坐标的距离dist2;
3、取得两个距离的比值rate = dist2/dist1;
4、物体的scale = node.scale * rate
5、如果不想让物体的尺寸被无限放大或者无限缩小至0,那么需要设置rate的最大最小值,让物体的尺寸控制在一个范围;
6、有一点需注意,触点坐标和物体坐标需转换至同一坐标系下
代码:

onload(){
this.touch_time = 0 // 用于控制物体的坐标等于第一次touch_start时的物体所在的坐标
},
 touch_start(event) {
        if (this.touch_time > 1) {
            this.node_position = this.node.getChildByName('decorate').position
        }
        this.decorate_node_scale = this.decorate_node.scale
        this.touch_location = event.getLocation()
        let nodePos = this.node.convertToNodeSpaceAR(this.touch_location)
        this.nodeX = this.node_position.x
        this.nodeY = this.node_position.y
        this.dist1 = cc.v2(this.nodeX, this.nodeY).sub(nodePos).mag();// 计算touch_start的触点与物体坐标的距离
    },

    touch_move(event) {
        this.touch_time++
        this.touch_location2 = event.getLocation()
        let nodePos = this.node.convertToNodeSpaceAR(this.touch_location2)
        this.dist2 = cc.v2(this.nodeX, this.nodeY).sub(nodePos).mag();// 计算移动过程中的触点坐标与物体坐标的距离




        let decorate_node = this.node.getChildByName('decorate') // 被控制物体
        let rate = this.dist2 / this.dist1 // 距离比值
        // 控制比值的最大不大于3,最小不小于0.5
        if (rate > 3) {
            rate = 3
        } else if (rate <= 0.5) {
            rate = 0.5
        }
        this.decorate_node.scale = this.decorate_node_scale * rate
        },

本人为行业新人,欢迎各位朋友在评论中分享你们的真知灼见。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值