Quick-cocos2d-x Beginner's Game tutorial (12)------------Touch events

Source: Internet
Author: User
Tags addchild

Quick-cocos2d-x Beginner's Game tutorial (12)

In the previous chapter we explained the collision detection between objects, and at the beginning of this chapter we will explain the implementation of touch events, and we will also add a blood bar to the Player.

Requirements Description

Before we get started, let's take a look at some of the game's needs in this section.

For this tutorial game, our requirement is to give the Player an upward speed when tapping the screen, so that it can fly, otherwise it will fall down by the impact of gravity. When dropped to the ground, the player loses blood, so we have to keep tapping the screen to prevent the player from falling to the ground. While avoiding player drops, we can also dodge obstacles and pick hearts by controlling the player's fly-up and landing.

The game started after the player energetic, full of blood, but when the player hit obstacles and the ground, will be based on the type of collision to deduct different points of blood, when the player hit heart, can increase a certain amount of blood, and will eliminate the heart, eliminate the same time give it a elimination effect, This special utility particle system to complete. The game ends when the player's blood volume is 0 or the map cannon.

After the requirement analysis is clear, we will begin to implement the functions described below.

Adding Touch events

First, let's add touch events.

Touch response is a very important module in game development, which is the main way for players to interact with the game in hand. In Quick, touch event mechanism is very simple, it allows any Node to accept touch events, not limited to Layer.

In our game, we need to start the response of the touch event when the Player starts falling, so we will start the response to the touch event in the Startdrop method of the Playerflytoscene function, as shown in the following code:

Local functionStartdrop() Self.Player:Getphysicsbody():Setgravityenable(True) Self.Player:Drop() Self.Backgroundlayer:Startgame() Self.Backgroundlayer:Addnodeeventlistener(Cc.Node_touch_event, function(Event) return self: ontouch (event. Name, event., event. end) self. Backgroundlayer:settouchenabled (true< Span class= "pun" >) end         

Here, we add a touch event listener to the Self.backgroundlayer background layer, where the Addnodeeventlistener method is used to register the listener for system events, such as touch events on the top, as well as frame events, key events, and so on.

You may ask: why is it that you are listening to Self.backgroundlayer to add touch events, why not the self scene itself, or the Player? What we need to explain here is that the touch response does not directly add an event listener to the scene, and if you only add touch listening to the player, then we can only respond to touch events in a very small range of the player, so we need a layer to do it. There is only one background layer created in the game, so we will add the listener to the touch event. Of course, you can also create a new layer to add touch monitoring, here we are not so fastidious!

The Settouchenabled method is used to turn on the touch function, and if settouchenabled (false), then the background layer will not accept the touch response.

In addition, the OnTouch method is a touch event callback, which is defined as follows:

function Gamescene:OnTouch(Event,X,Y) If Event == "Began" Then Self.Player:Flying() Self.Player:Getphysicsbody():SetVelocity(Cc.P(0, 98)) Return True --ElseIfEvent ==  "moved"  then ElseIf Span class= "KWD" >event ==  "ended"  then self.:drop ()  -- else event==  "cancelled"  then< Span class= "PLN" > endend      

Because we want to achieve a click on the screen to give the player an upward speed, no point when the player drops down. So, here we just have to get the player to fly and give it a direction up (0, 98) at the beginning of the touch, and let the player drop when the touch is over. Instead of having to consider the state of moving "moved" and touching cancel "cancelled" in touch.

Another thing to note is that you must return true at the beginning of the touch, otherwise messages such as "ended" will not be answered.

Add a blood Bar

Next, we'll add a blood bar to the Player, which can be done with the already encapsulated progress bar (Progresstimer) in the engine.

Here's the code we added in the Player, let's take a look at it first.

function Player:Createprogress() Self.Blood= 100 -- 1 LocalProgressbg=Display.Newsprite("#progress1. png") -- 2 Self.Fill=Display.Newprogresstimer("#progress2. png",Display.Progress_timer_bar) -- 3 Self.Fill:Setmidpoint(Cc.P(0, 0.5)) -- 4 Self.Fill:Setbarchangerate(Cc.P(1.0, 0)) -- 5 -- 6 Self.Fill:SetPosition(Progressbg:Getcontentsize().Width/2,Progressbg:Getcontentsize().Height/2)Progressbg:AddChild(Self.Fill) Self.Fill:Setpercentage(Self.Blood) -- 7 -- 8Progressbg:Setanchorpoint(Cc.P(0, 1)) Self:GetParent():AddChild(Progressbg)Progressbg:SetPosition(Cc.P (display. Left, Display.endfunction< Span class= "PLN" > player:setpropercentage  (percentage)  self< Span class= "pun". fill:setpercentage ( Percentage  -- 9end             

The function of the Createprogress method is to add a progress bar, and the Setpropercentage method is to set the percentage of the progress bar. Here we explain the code:

  1. Add the blood volume attribute Self.blood, here the initial value I set to 100, so that we can be based on the amount of blood to set the percentage of the progress bar (lazy practice).
  2. Create a bottom for the progress bar, which is to put a background under the progress bar so that when the progress bar becomes shorter, the user can see more intuitively how much it is reduced.
    The progress bar background and the progress bar picture are as follows:
  3. Create a progress bar the two parameters of the Self.fill,display.newprogresstimer method represent the picture used to create the progress bar, and the type of the progress bar. There are two types of progress bars in the engine:
    • Display. Progress_timer_bar: Bar, this type of progress bar is typically used to create a class of progress bars similar to the life bar, level bar.
    • Display. Progress_timer_radial: Ring, it is usually used to create a similar loading function of the progress bar, such as the game loading resources when the page rotation of chrysanthemum (PS: Word poor, is the Chrysanthemum bar, do not think crooked).
  4. Sets the starting point of the progress bar, (0,y) represents the leftmost, (1,y) represents the rightmost, (x,1) represents the topmost, (x,0) represents the bottom.
  5. Sets the direction of the progress bar change, if not the direction of the change, set the direction is 0, otherwise set to 1. So (1,0) indicates the transverse direction, (0,1) indicates the longitudinal direction.
  6. Set the position of the progress bar on the PROGRESSBG and add the progress bar to the PROGRESSBG.
  7. Call Progresstimer's Setpercentage method to set the percentage of the progress bar to 100% (because the value of Self.blood is 100).
    The Progresstimer class has a much-needed percentage property. It represents the progress value of the current progress bar. Where the Setpercentage method can set the percentage value of the Progresstimer.
  8. Add the PROGRESSBG to the upper-left corner of the screen. Here are three things to do:
    • First of all, the PROGRESSBG anchor is set to its upper-left corner, the concept of Anchor point I forgot to say before, here or simply explain.
      The two parameters of the anchor point are between 0~1. The default value of the anchor point for a generic node is (0.5, 0.5), which is the middle of the node. (0, 1) represents the upper-left corner, when a node is added to the parent node, it is necessary to set the position of the node on the parent node, which is essentially the position of the anchor point of the Set node in the parent node's coordinate system.
    • We then added the PROGRESSBG to the Player's parent node, which is also the gamescene scene. This way, the progress bar does not move as the Player moves.
    • Finally, here we put the PROGRESSBG in the upper left corner of the screen.
  9. Setpropercentage We're going to set the percentage of the progress bar.

Well, the code snippet above to create the blood bar should be explained enough, so what we need to do next is call it in the right place. Here we call in the Gamescene:

Self.Player= Player.New()Self.Player:SetPosition(-20, Display.* 2 /  3) self :addchild (self.player) self: playerflytoscene () self player:createprogress ()  -- here          

Now, running the game, we can see the following effect.

OK, this chapter is everywhere, the next chapter will be the last chapter of our tutorial, the full code you expect to release, please look forward to it.

Reprint please specify from: http://shannn.com/archives/437

Quick-cocos2d-x Beginner's Game tutorial (12)------------Touch events

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.