Cocos2d/Python:层的可视部分与焦点方向相反移动

0 投票
1 回答
703 浏览
提问于 2025-04-18 08:47

我是个新手,正在用Python和Cocos2d 0.6.0制作一个游戏 :)

我正在使用ScrollingManager的set_focus(x, y)方法,通过鼠标在一个2D瓦片地图上滚动。涉及的层似乎滚动得很正常,但有一个和窗口大小(512x512)一样的裁剪层,朝相反的方向移动,部分遮挡了我的层。我该怎么让这个裁剪层消失呢?

我可以这样更好地理解这个问题:

截图1:启动时的初始焦点,所有层都可见

截图2:向下滚动后,层似乎被裁剪了

作为参考,我正在使用Cocos2d 0.6.0的ScrollingManager类来进行Python编程。

[编辑] 我创建了一个独立的脚本,可以进行测试。

import pyglet
from pyglet.window import key, mouse
import cocos
from cocos import tiles, actions, layer
import random

def main():
  global mouse, scroller
  global fx, fy, winx, winy, offsetx, offsety

  # map size (cells)
  hsize = 128
  vsize = 128

  # window size (pixels)
  winx = 960
  winy = 640

  # coordinates of screen focus
  fx = 0
  fy = 0

  from cocos.director import director
  director.init(width=winx, height=winy, do_not_scale=True, resizable=True)

  offsetx = hsize * 16 - winx
  offsety = vsize * 16 - winy

  ##################################
  ### creation of randomized map ###
  ##################################

  tileset = {}
  # a 16x16 pixel tile (blue, represents water)
  tileset['water']  = pyglet.image.ImageGrid(pyglet.image.load('resources/water.png'), 4, 4)
  # a 16x16 pixel tile (green, represents land)
  tileset['land']   = pyglet.image.ImageGrid(pyglet.image.load('resources/land.png'), 4, 4)

  # empty 2D array holding RectCells
  cellMatrix = [ [None]*hsize for i in range(vsize) ]

  # filling of array
  for v in range(vsize):
    for h in range(hsize):
      if random.random() < 0.5:
        image = tileset['water'][1]
      else:
        image = tileset['land'][1]

      tile = cocos.tiles.Tile('test', {}, image, None)

      cellMatrix[v][h] = cocos.tiles.RectCell(h*16, v*16, 1, 1, None, tile)

  ##################################
  ### end of creating random map ###
  ##################################

  # creating rectMapLayer from cell array
  rectMapLayer = cocos.tiles.RectMapLayer('test', 16, 16, cellMatrix, None, {})

  scroller = cocos.layer.ScrollingManager()
  scroller.add(rectMapLayer, 0, 'test')
  main_scene = cocos.scene.Scene(scroller)

  def on_mouse_motion(x, y, dx, dy):

    global fx, fy, offsetx, offsety, winx, winy

    if x > winx - 16:
      fx = min(offsetx, fx + 16)

    if x < 16:
      fx = max(0, fx - 16)

    if y > winy - 16:
      fy = min(offsety, fy + 16)

    if y < 16:
      fy = max(0, fy - 16)

    scroller.set_focus(fx + winx/2, fy + winy/2, force=True)

  director.window.push_handlers(on_mouse_motion)

  director.run(main_scene)

# run game
if __name__ == '__main__':
  main()

谢谢大家的回答!

1 个回答

0

通过改变每一层的视图来解决了这个问题,具体做法如下:

rectMapLayer = cocos.tiles.RectMapLayer('test', 16, 16, cellMatrix, None, {})

scroller = cocos.layer.ScrollingManager()

scroller.add(rectMapLayer, 0, 'test_layer')

# focus coordinates
x = 50
y = 50

scroller.get('test_layer').set_view(0, 0, 1024, 1024, -x, -y)

这样做会让测试层的视图从原点(0, 0)开始,宽度和高度都是1024x1024,并且会有一个-x和-y的偏移。

撰写回答