cocos2d-x笔记(十一)Lua开发飞机大战-5-让飞机动起来

再上一篇已经将飞机添加到了游戏,下一步就要让它动起来。主要要响应触摸事件。

在C++中通过重写ccTouchBegan()、ccTouchMoved()、ccTouchEnded()三个函数来响应触摸事件。在Lua只需将响应函数注册到分发器中就可以了。

1.先设置该图层可以触摸,然后注册响应函数onTouch

	gameLayer:setTouchEnabled(true)
	gameLayer:registerScriptTouchHandler(onTouch)

2.onTouch函数有3个参数,第一个是事件的类型(began、moved、ended),后面两个参数就不用多说了。

function onTouch(eventType, x, y)
	if eventType == "began" then   
		return onTouchBegan(x, y)
	elseif eventType == "moved" then
		return onTouchMoved(x, y)
	else
		return onTouchEnded(x, y)
	end
end

3.分别实现3个触摸事件

local touchBeginPoint = nil
function onTouchBegan(x, y)
	touchBeginPoint = {x = x, y = y}
	return true
end

function onTouchMoved(x, y)
	if PlaneLayer.alive() and PlaneLayer.containsTouchLocation(x,y) then 
		--local offset = ccpSub(ccp(touchBeginPoint['x'],touchBeginPoint['y']),ccp(x,y))
		--local toPoint = ccpAdd(ccp(PlaneLayer.getPlane():getPositionX(),PlaneLayer.getPlane():getPositionY()),offset)
		PlaneLayer.moveTo(x,y)
	end
end

function onTouchEnded(x, y)
	
end



4.在onTouchMoved函数中出现了一个没见过的函数PlaneLayer.containsTouchLocation(x,y)。这个方法用来判断想触摸点是否在飞机的位置上。

function containsTouchLocation(x,y)
	local planeRect = plane:boundingBox()
	planeRect.origin.x = planeRect.origin.x - 15
	planeRect.origin.y = planeRect.origin.y - 15
	planeRect.size.width = planeRect.size.width + 30
	planeRect.size.height = planeRect.size.height + 30
    local b = planeRect:containsPoint(ccp(x,y))
    return b
end


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值