cocos2dx Moving a sprite with a physics scene - cocos2d-x

I have a scene init with physics and i have a character sprite with a physics body, then I have a static ground sprite with a physics body. That all works fine so my next step was to move my character. Now I assumed that if I just updated my characters X position the character would move and stay on the ground but if the ground drops off the character does not drop it just floats, how do i move my character sprite and have it stay on the ground at all times? The code for my update function is below
void LevelOne::update(float delta)
{
if (mJoystick->isActive())
{
Vec2 scaledVelocity = mJoystick->getVelocity() * 240;
Vec2 updatedPosition = Vec2(mCharacter->getPosition().x + scaledVelocity.x
* delta, mCharacter->getPosition().y);
mCharacter->setPosition(updatedPosition);
if (mJoystick->getVelocity().x < 0)
{
mCharacter->setFlippedX(false);
}
else
{
mCharacter->setFlippedX(true);
}
}

Following Steps can solve your problem-
1) Have you set the Gravity like gravity.Set(0.0f, -10.0f), y should be in negative.
2) Set you Character Sprite is Dynamic.
3) code should be in update method.
int32 velocityIterations = 1;
int32 positionIterations = 1;
world -> Step(dt, velocityIterations, positionIterations);
for (b2Body* b = world -> GetBodyList(); b; b = b -> GetNext()) {
if (b -> GetUserData() != NULL) {
CCSprite *myActor = (CCSprite*) b -> GetUserData();
if(myActor != NULL) {
myActor->setPositionY( b -> GetPosition().y * PTM_RATIO);
myActor->setRotation(-1 * CC_RADIANS_TO_DEGREES(b -> GetAngle()));
}
}
}

Related

How do I use mouselistener and press event to change a filled square to another color?

This is for homework, I have most of this done but I am stuck on the final step (implementing a mouse event that will change one of my randomized colored squares to become red instead of it's assigned colors) and am concerned that using the methods provided by my prof are not suitable to this, as he has us repaint after mouse event (which I feel my code will just override with more random colors). Any assistance or nudge in the right direction would be helpful, and I am sure this is a mess.
Update as per Camickr's assistance, my code has changed to the following:
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
// MouseListener Imports
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class Test extends JPanel implements MouseListener
{
static Color[][] framework = new Color[8][8];
static int redCounter = 0;
// main Creates a JFrame and instantiates the 2d array of color objects
public static void main(String[] args)
{
// The frame handles all the outside window work
JFrame frame = new JFrame("MouseListener demo");
// Allows the 'X' in the upper right to cause the program to exit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
// contentPane holds a panel
JComponent newContentPane = new Test();
// MouseListenerDemo isa JPanel isa JComponent
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
/* Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
The resulting width and height of the window are automatically enlarged if either of dimensions
is less than the minimum size as specified by the previous call to the setMinimumSize method.
If the window and/or its owner are not displayable yet, both of them are made displayable before
calculating the preferred size. The Window is validated after its size is being calculated.
*/
frame.setVisible(true);
for (int x = 0; x < framework.length; x++) {
for (int y = 0; y < framework.length; y++) {
Color rc = randomColor();
framework[x][y] = rc;
}
}
}
// Constructor
public Test()
{
// layout the panel with an area in which to draw
super(new GridLayout(0,1));
// get Graphics object, which allows you to draw on the panel
// set initial size of the panel
setPreferredSize(new Dimension(400, 500));
// ADD this JPanel to the list of components notified when a mouse event happens
this.addMouseListener(this);
// calls paint()
repaint();
}
// draws the screen
public void paint(Graphics g)
{
// Get the size
Dimension d = this.getSize();
int size = 50; // The edge length of the squares
int xSt = 50; // Starting x-coordinate
int ySt = 50; // Starting y-coordinate
int n = 8; // n X n board
int xPos, yPos;
for(int row = 0; row < framework.length; row ++){
for (int col = 0; col < framework.length; col ++){
xPos = xSt*col;
yPos = xSt*row;
// set color
g.setColor (framework[row][col]);
// Draw square
g.fillRect(xPos, yPos, size, size);
}
}
g.setColor(Color.black);
g.drawString("There are " + redCounter + " reds." , d.width/3, d.height);
}
public static Color randomColor(){
Random rg = new Random();
int result = rg.nextInt(12);
Color color;
switch(result){
case 0: color = Color.black;
break;
case 1: color = Color.blue;
break;
case 2: color = Color.cyan;
break;
case 3: color = Color.darkGray;
break;
case 4: color = Color.yellow;
break;
case 5: color = Color.green;
break;
case 6: color = Color.lightGray;
break;
case 7: color = Color.magenta;
break;
case 8: color = Color.orange;
break;
case 9: color = Color.pink;
break;
case 10: color = Color.red; redCounter = redCounter + 1;
break;
case 11: color = Color.white;
break;
default: color = Color.black;
break;
}
return color;
}
// MouseListener methods
public void mousePressed(MouseEvent evt)
{
// demonstrates how to use the parameter
// to get the position of the mouse press
Dimension d = this.getSize();
int x = evt.getX();
int y = evt.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
System.out.println(evt.getSource());
for (int i = 0; i < framework.length; i++) {
for (int j = 0; j < framework.length; j++) {
System.out.println(framework[i][j]);
if (evt.getSource().equals(framework[i][j])) {
framework[i][j] = Color.red;
redCounter = redCounter + 1;
}
}
}
repaint(); // redisplay the frame by eventually calling the paint() method
}
// do nothing for the other mouse actions
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
am concerned that using the methods provided by my prof are not suitable to this, as he has us repaint after mouse event (which I feel my code will just override with more random colors).
The repaint() in the MouseEvent is correct. However more random colors will be generated because your painting code is incorrect.
A painting method should only paint the state of your component, not change the state. Therefore:
You need to keep a data structure (lets say a 2D array) to hold the Color of each cell. In the constructor of your class you would then iterate through this array and assign the random colors to each entry in the array.
Then in the painting method you just iterate through the array and paint each cell using the color from the array.
Note you should be overriding paintComponent(), not paint() for the custom painting.
Then in your MouseListener code you just reset the Color in the Array for the cell that was clicked and invoke repaint().
I fixed it by getting the position of x/y and dividing them by 50 (my square height/width) and putting the int into the array index.
public void mousePressed(MouseEvent evt)
{
// demonstrates how to use the parameter
// to get the position of the mouse press
Dimension d = this.getSize();
int x = evt.getX()/50;
int y = evt.getY()/50;
framework[y][x] = Color.red;
redCounter = redCounter+1;
repaint(); // redisplay the frame by eventually calling the paint() method
}

How to achieve the following effect with libGDX?

I'm developping a game with libGDX. I have a question: Know the initial coordinates and target coordinates, as the picture shows, how to achieve the parabolic effect of the bullet ? to achieve the operation of shells . Who can teach me ? or tell me some tutorial. Tks
picture
You need to add some physics to your app (ex. Box2d). Then you 'throw' canon ball with some velocity and some direction/angle.
Physics engine do rest for you.
Here you have tutorial for box2d: https://www.youtube.com/watch?v=vXovY2KTing
Very very basic example for throw something without box2d. For your example you need to calculate right 'power' for target position.
public class SampleApp extends ApplicationAdapter
{
Sprite sprite;
Vector2 velocity = new Vector2(0, 0);
Vector2 terminateVelocity = new Vector2(2000, 2000);
Vector2 friction = new Vector2(200, 300);
Vector2 position = new Vector2(0, 0);
Vector2 launchPower = new Vector2(0, 0);
boolean shotNow;
#Override
public void render()
{
update(Gdx.graphics.getDeltaTime());
// ...
// here render your stuff
}
public void shot(float power)
{
// Calculate x launch power
launchPower.x = ((power - sprite.getX() + sprite.getWidth()*0.5f) / 2f) + velocity.x;
// We want to end our fly at ground
launchPower.y = ((0 - sprite.getY()) / 2f) + velocity.y;
// Setup start position
position.x = sprite.getX();
position.y = sprite.getY();
// Add some acc to velocity
velocity.add(launchPower);
shotNow = true;
}
public void update(float dt)
{
if (Gdx.input.justTouched()) {
shot(900);
}
// Very basic sprite movement.
// For best results you should implement more physics (acceleration etc.)
if (shotNow && position.y > 0) {
// Friction/gravity
velocity.x = MathUtils.clamp(velocity.x - friction.x * dt, -terminateVelocity.x, terminateVelocity.x);
velocity.y = MathUtils.clamp(velocity.y - friction.y * dt, -terminateVelocity.y, terminateVelocity.y);
position.add(velocity.x * dt, velocity.y * dt);
sprite.setPosition(position.x, position.y);
}
}
}

Processing: How do i create an object every "x" time

What I want to do is to create a new planet in my system for example every 10 seconds and that it starts to move and also prints a "hello" . At the end I want that the 8 planets (ellipses) will be moving together.
I try to use delay(); but I failed .
Can someone help me please?
Planet [] planetCollection = new Planet [8];
float [] wid2 = {100,200,300,400,500,600,700,800};
float [] hig2 = {50,75,100,125,150,175,200,225};
int [] colorR = {100,800,300,400,500,600,700,800};
int [] colorG = {50,225,100,125,150,175,200,225};
int [] colorB = {50,225,100,125,150,175,200,225};
int [] size = {10,12,14,16,18,20,22,24};
int lastTime =0;
int contador =0;
void setup (){
size (1600,1600);
smooth();
//INITIALIZE
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i] = new Planet(wid2[i], hig2[i], colorR[i],
colorG[i], colorB[i], size[i]);
}
}
void draw (){
background (0);
//CALL FUNCIONALITY
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i].run();
}
}
class Planet {
//GLOBAL VARIABLES
float val;
float x = 0;
float y = 0;
float wid2;
float hig2;
float speed;
int colorR;
int colorG;
int colorB;
int size;
int centerx = width/2;
int centery = height/4;
//CONTRUCTOR
Planet(float _w, float _h,int _colorR,int _colorG,int _colorB, int _size){
wid2=_w;
hig2=_h;
colorR= _colorR;
colorG= _colorG;
colorB= _colorB;
size = _size;
speed=10/(2*PI * sqrt ((pow(wid2,2)+pow (hig2,2)/2))); ;
}
//FUNCTIONS
void run (){
move();
display();
}
void move (){
x= sin (val);
y= cos(val);
x *=wid2;
y *=hig2;
//SUN/CENTER
noStroke();
fill (255,238,41);
ellipse (centerx,centery,40,40);
if (dist (mouseX,mouseY,centerx,centery)<20){
if(mousePressed){
speed =0;
}
}
//
x+= centerx;
y+= centery;
val += speed;
}
void display (){
//PLanets
fill(colorR, colorG, colorB);
ellipse(x, y, size, size);
///Orbits
noFill();
stroke(255);
ellipse(centerx, centery, wid2*2, hig2*2);
println ("posicionx "+x);
println ("posiciony "+y);
println ("width "+wid2);
println ("high "+hig2);
println ("val "+val);
println ("speed "+speed);
}
}
You can use the modulo % operator along with the frameCount variable inside the draw() function to do something every X frames.
Here is an example program that draws little circles most frames, but draws a big circle every 60 frames:
void setup() {
size(500, 500);
background(0);
}
void draw() {
ellipse(mouseX, mouseY, 10, 10);
if (frameCount % 60 == 0) {
ellipse(mouseX, mouseY, 50, 50);
}
}
You can build a timer for counting seconds using a helper variable and the in-built variable frameRate. (Note that this solution ensures that you truly count seconds independent on your machine's current workload.)
frameRate tells you how many cycles Processing is currently performing per second (one cycle = one execution of draw, also called one frame). This is usually 60 (frames per second) but can also be lower depending on other processes on your machine (e.g. when running video processing, 3D games etc. the frame rate goes down).
Here's a snippet to see what your current frameRate is:
void draw() {
println(frameRate);
}
And here's the timer using a helper variable counter which is reset every second. You should see a new dot appear on the console output every second.
int counter = 0;
void draw() {
if (counter > frameRate) {
print(".");
counter = 0;
} else {
counter++;
}
}
To make it count every 10 seconds you can just change the if condition to "counter > 10 * frameRate".

Resetting a players x position (Flash As3)

private function scrollStage():void
{
if (lastPosX != lastPosX)
{
canScrollStage = false;
}
else
if (lastPosX == lastPosX)
{
canScrollStage = true;
}
if (canScrollStage)
{
if (rightKey)
{
//move background left
//something.x +=(stage.stageWidth * 0.5) - character.x * 2;
}
else
if (leftKey)
{
//move backgrounf Roight
}
for (var b:int = 0; b < childrenOnStage; b++)
{
if (getChildAt(b).name == "enemy")
{
getChildAt(b).x +=(stage.stageWidth * 0.5) - character.x
}
}
ground.x += (stage.stageWidth * 0.5) - character.x
}
else
{
//move the background
}
// do this last, everything moves around object
character.x = stage.stageWidth * 0.5;
lastPosX = character.x;
}
Someone told me to move the objects around the player and then update the players x position.
This is what I've done by looking at a tutorial ("Cartoon Smart");
In my player class I have a reset function.
private var xSpeed:int;
private var resetPos:Point;
public function player()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd)
}
private function onAdd(e: Event): void
{
xSpeed = 3;
resetPos = new Point(x, y);
}
public function reset():void
{
x = resetPos.x;
y = resetPos.y;
//trace(resetPos);
//trace(resetPos + "player");
}
When the player falls to death this function is called
private function playerFalls():void
{
if (character.y > stage.stageHeight)
{
//take life away and go back to check point or back to reset
character.x = stage.stageWidth * 0.5;
character.y = 20;
//goblin1.reset();
//goblin2.reset();
//goblin3.reset();
//stage.x = stage.stageWidth * 0.5;
//canScrollStage = false;
}
}
if I use
character.x = stage.stageWidth * 0.5;
Then my character ends up in the middle, but it will end up in the middle since the scroll function dictates the player to be in the center always.
character.x = (stage.stageWidth * 0.5) - 400;// moves him back
but if character falls off left of the screen then he is moved back.
Any one have a solution for this please?
My question is, I want to reset the player's x position to 300 and y position to 10;
But I can't do this because the stage shifts and the co ordinate system changes.
In order for the player to go back to the original coordinate of the stage, the stage must scroll.
That's my idea, or perhaps the ground and enemies must do the opposite?
I sincerely apologize for the late answer. Okay, so your saying that when the character falls you don't want the screen to scroll all the way back to the character's start position. What you need to do is find the start positions of your character and ground (as well as any other layers such as backgrounds etc). Then wherever your fall function comes into place simply set the character and background positions to their starting coordinates.
function fall(){
char.x=charStartX;
char.y=charStartY;
ground.x=groundStartX;
ground.y=groundStartY;
//etc
}
For example, let's say you have a check point. If player hits check point charResetPoint = 100. If player falls then set it's x pos to charResetPoint
But I can't move the players x position because it will always be stage.stageWidth/2 due to my code.
So in theory it will be difficult to make a resetPoint, because when I add goblin 1.x , it's x pos is 900, if I scroll right goblon1 x pos will change. Everythings x pos changes and so does the stages.
I can't get a grasp on the concept, sortlry

How to make a sliding menu in cocos2dx in c++ for IOS game

I want to make a sliding menu just like the level menu in which on one screen there will be 40 sprites labelled as level 1 level 2 respectively up to 40.
At the bottom right there will be another sprite with a arrow to which when I click it should slide to other screen and show the levels 41 to 80.Please provide me with a basic concept how to use it.I will be thankful to you.
Note: I am using Xcode and ony want solution in cocos2d-x using c++
This is the way I have done this in the past...I had a game with the option for the player to select multiple space ships, 4 per page, with back/forward arrows on each page as well.
Create a CCScene derived class.
Place all your menu items, including the control arrows for ALL pages on it. You will have to space all the items so the items for the first page are on the visible part of the screen and the next group is 100% off to the right, the third group is 200% off the right, etc.
The control buttons on the scene start an action to move the layer 100% to the left (if they move right) or 100% to the right (if they move left).
All of these are attached to a single "Menu", which is what the actions are applied against. If you want, you can put the menu into a layer (so it has background that moves). This is up to you.
In the example Scene below, I just used a simple menu.
MainScene.h
#ifndef __MainScene__
#define __MainScene__
#include "cocos2d.h"
using namespace cocos2d;
class MainScene : public CCScene
{
private:
// This class follows the "create"/"autorelease" pattern.
// Private constructor.
MainScene();
CCMenu* _menu;
bool _sliding;
void MenuCallback(CCObject* sender);
void PageLeft();
void PageRight();
void SlidingDone();
protected:
// This is protected so that derived classes can call it
// in their create methods.
bool init();
private:
void CreateMenu();
public:
static MainScene* create();
~MainScene();
virtual void onEnter();
virtual void onExit();
virtual void onEnterTransitionDidFinish();
virtual void onExitTransitionDidStart();
};
#endif /* defined(__MainScene__) */
MainScene.cpp
#include "MainScene.h"
#define ARROW_LEFT (-1)
#define ARROW_RIGHT (-2)
#define MENU_ITEMS_ACROSS 4
#define MENU_ITEMS_DOWN 5
#define MENU_ITEMS_PAGE (MENU_ITEMS_ACROSS*MENU_ITEMS_DOWN)
#define MENU_ITEMS_TOTAL 50
#define MENU_PAGES ((MENU_ITEMS_TOTAL/MENU_ITEMS_PAGE)+1)
#define MENU_FRACTION (ccp(0.8,0.8))
#define MENU_ANCHOR (ccp(0.5,0.5))
#define SLIDE_DURATION 1.0
MainScene::MainScene() :
_menu(NULL)
_sliding(false)
{
}
MainScene::~MainScene()
{
}
static CCPoint CalculatePosition(int itemNum)
{
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
float Xs = scrSize.width;
float Ys = scrSize.height;
int gRows = MENU_ITEMS_DOWN;
int gCols = MENU_ITEMS_ACROSS;
int gBins = gRows*gCols;
float Xb = MENU_FRACTION.x*Xs/gCols;
float Yb = MENU_FRACTION.y*Ys/gRows;
float Xa = MENU_ANCHOR.x * Xs;
float Ya = MENU_ANCHOR.y * Ys;
int page = itemNum / gBins;
int binCol = itemNum % gCols;
int binRow = (itemNum-page*gBins) / gCols;
float xPos = binCol * Xb + Xb/2 + Xa - MENU_FRACTION.x*Xs/2 + page * Xs;
float yPos = Ya - binRow*Yb - Yb/2 + MENU_FRACTION.y * Ys/2;
CCPoint pos = ccp(xPos,yPos);
return pos;
}
void MainScene::CreateMenu()
{
if(_menu == NULL)
{
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
_menu = CCMenu::create();
_menu->setPosition(ccp(0,0));
addChild(_menu);
CCMenuItemFont* pItem;
CCPoint position;
// Create the next/back menu items.
for(int page = 0; page < MENU_PAGES; page++)
{
// Create the Back/Forward buttons for the page.
// Back arrow if there is a previous page.
if(page > 0)
{
pItem = CCMenuItemFont::create("Back", this, menu_selector(MainScene::MenuCallback));
pItem->setTag(ARROW_LEFT);
position = ccp(page*scrSize.width + scrSize.width*0.1,scrSize.height*0.1);
pItem->setPosition(position);
pItem->setFontSize(35);
pItem->setFontName("Arial");
_menu->addChild(pItem);
}
if(page < (MENU_PAGES-1))
{
pItem = CCMenuItemFont::create("Next", this, menu_selector(MainScene::MenuCallback));
pItem->setTag(ARROW_RIGHT);
position = ccp(page*scrSize.width + scrSize.width*0.9,scrSize.height*0.1);
pItem->setPosition(position);
pItem->setFontSize(35);
pItem->setFontName("Arial");
_menu->addChild(pItem);
}
}
// Create the actual items
for(int idx = 0; idx < MENU_ITEMS_TOTAL; idx++)
{
char buffer[256];
sprintf(buffer,"Item #%d",idx);
pItem = CCMenuItemFont::create(buffer, this, menu_selector(MainScene::MenuCallback));
pItem->setFontSize(35);
pItem->setFontName("Arial");
pItem->setTag(idx);
position = CalculatePosition(idx);
pItem->setPosition(position);
_menu->addChild(pItem);
}
}
}
bool MainScene::init()
{
return true;
}
MainScene* MainScene::create()
{
MainScene *pRet = new MainScene();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
CC_SAFE_DELETE(pRet);
return NULL;
}
}
void MainScene::onEnter()
{
CCScene::onEnter();
CreateMenu();
}
void MainScene::onExit()
{
CCScene::onExit();
}
void MainScene::onEnterTransitionDidFinish()
{
CCScene::onEnterTransitionDidFinish();
}
void MainScene::onExitTransitionDidStart()
{
CCScene::onExitTransitionDidStart();
}
void MainScene::SlidingDone()
{
_sliding = false;
}
void MainScene::PageLeft()
{
if(_sliding)
return;
_sliding = true;
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
CCFiniteTimeAction* act1 = CCMoveBy::create(SLIDE_DURATION, ccp(scrSize.width,0));
CCFiniteTimeAction* act2 = CCCallFunc::create(this, callfunc_selector(MainScene::SlidingDone));
_menu->runAction(CCSequence::create(act1,act2,NULL));
}
void MainScene::PageRight()
{
if(_sliding)
return;
_sliding = true;
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
CCFiniteTimeAction* act1 = CCMoveBy::create(SLIDE_DURATION, ccp(-scrSize.width,0));
CCFiniteTimeAction* act2 = CCCallFunc::create(this, callfunc_selector(MainScene::SlidingDone));
_menu->runAction(CCSequence::create(act1,act2,NULL));
}
void MainScene::MenuCallback(CCObject* sender)
{
// This is a very contrived example
// for handling the menu items.
// -1 ==> Left Arrow
// -2 ==> Right Arrow
// Anything else is a selection
CCMenuItem* pMenuItem = (CCMenuItem*)sender;
switch(pMenuItem->getTag())
{
case ARROW_LEFT:
PageLeft();
break;
case ARROW_RIGHT:
PageRight();
break;
default:
CCLOG("Got Item %d Pressed",pMenuItem->getTag());
break;
}
}
Note The formulas for getting the items spread across several pages can be a little tricky. There is a notion of "Screen fraction", which is how much the grid of items takes up on the page. There is also the notion of "menu anchor", which where on the page you want the grid to be.
Some screen shots
or you can do it the modern way with less code!!
// you have to include this header to use the ui classes
#include "ui/CocosGUI.h"
using namespace ui;
#define COLS 4
#define ROWS 4
#define ITEMS_PER_PAGE (ROWS * COLS)
#define TOTAL_PAGES_NUM 10
#define MENU_PADDING (Vec2(0.8,0.8))
#define MENU_ANCHOR (Vec2(0.5,0.5))
static Vec2 calcPosition(int itemNum)
{
Size scrSize = Director::getInstance()->getWinSize();
float Xs = scrSize.width;
float Ys = scrSize.height;
float Xb = MENU_PADDING.x*Xs / COLS;
float Yb = MENU_PADDING.y*Ys / ROWS;
float Xa = MENU_ANCHOR.x * Xs;
float Ya = MENU_ANCHOR.y * Ys;
int page = itemNum / ITEMS_PER_PAGE;
int binCol = itemNum % COLS;
int binRow = (itemNum - page * ITEMS_PER_PAGE) / COLS;
float xPos = binCol * Xb + Xb / 2 + Xa - MENU_PADDING.x*Xs / 2 + page * Xs;
float yPos = Ya - binRow*Yb - Yb / 2 + MENU_PADDING.y * Ys / 2;
return Vec2(xPos, yPos);
}
//init method
// pageView is the container that will contain all pages
auto pageView = PageView::create();
pageView->setContentSize(winSize);
//if you want pages indicator just uncomment this
//pageView->setIndicatorEnabled(true);
//pageView->setIndicatorPosition(some position);
//pageView->setIndicatorSelectedIndexColor(some Color3B);
for (int i = 0; i < TOTAL_PAGES_NUM; i++) {
auto layout = Layout::create();
layout->setContentSize(winSize);
// give each page a different random color
int r = rand() % 200;
int g = rand() % 200;
int b = rand() % 200;
auto bg = LayerColor::create(Color4B(Color3B(r, g, b)), winSize.width, winSize.height);
layout->addChild(bg, 0);
// populate each single page with items (which are in this case labels)
for (int i = 0; i < ITEMS_PER_PAGE; i++) {
auto label = LabelTTF::create(StringUtils::format("item %i", (i + 1)), "Comic Sans MS", 15);
Vec2 pos = calcPosition(i);
label->setPosition(pos);
layout->addChild(label, 1);
}
pageView->addPage(layout);
}
this->addChild(pageView);
I’ve modified existing one and uploaded in github. Here is the link:
GitHub Link to SlidingMenu
You may find it helpful. You can directly add it into your game.