CocosCreator camera zoomed move coordinate transformation

Summary

After the lower-left corner of the screen based on the coordinates of the touch event in CocosCreator of origin, then we do move the zoom in the camera coordinate how to handle it?

text

Use version

CocosCreator version v2.2.1

Presentation Layout

A main camera, a management node nine square blocks and blocks node size is 600 * 600, only the blocks can be bound to the event.

Event Listeners

We write a listener function, print coordinates.

onLoad () {
    this.blocks.on(cc.Node.EventType.TOUCH_END, (event) => {
        const pos = event.getLocation()
        const x = Math.floor(pos.x / 200)
        const y = Math.floor(pos.y / 200)
        cc.log(pos)
        cc.log(x, y)
    }, this)
}

As shown, the lower left corner is 0,0 then the size of each block is 200 * 200, rounding get subscript (I clicked on (2,2) region) after doing the division.

Zoom change

Change in the start of the main camera.

start () {
    this.mainCamera.zoomRatio = 2
}

As shown, although I clicked on the (1,1) of the area, but the display is still the (2,2) position as clickable screen coordinates unchanged.

Screen coordinates to world coordinates

Clearly, we need to coordinate transformation and camera assembly is to have this API, we modify the event code.

this.blocks.on(cc.Node.EventType.TOUCH_END, (event) => {
    const pos = event.getLocation()
    // 转化
    let realPos = cc.v2(0, 0)
    this.mainCamera.getScreenToWorldPoint(pos, realPos)
    const x = Math.floor(realPos.x / 200)
    const y = Math.floor(realPos.y / 200)
    cc.log(pos, realPos)
    cc.log(x, y)
}, this)

As shown, although the click position (2,2) in screen coordinates, but after the conversion is based on the coordinates of the game world, and normal (1,1).

Location change

If we change the camera position do?

start () {
    this.mainCamera.node.setPosition(cc.v2(100, 0))
    this.mainCamera.zoomRatio = 0.5
}

Or the right, because the conversion of this API are handled well.

Epilogue

One thing to note, getScreenToWorldPoint this method is a new method 2.1 or later. When using getCameraToWorldPoint the old method, the display has been deprecated in version 2.2.

Learn it! O (∩_∩) O ~~

Micro-channel public number

Published 124 original articles · won praise 137 · Views 150,000 +

Guess you like

Origin blog.csdn.net/kuokuo666/article/details/104131738