Hi in this game that i am trying to modify there are 3 different types of enemies all with the same enemyHealth script. in this health script i am attempting to increase a counter every time an enemy dies. the code below shows the enemyHealth class
using UnityEngine;
namespace CompleteProject
{
public class EnemyHealth : MonoBehaviour
{
public int startingHealth = 100; // The amount of health the enemy starts the game with.
public bool isDead; // Whether the enemy is dead.
public int deathCount;
public int currentHealth; // The current health the enemy has.
public float sinkSpeed = 2.5f; // The speed at which the enemy sinks through the floor when dead.
public int scoreValue = 10; // The amount added to the player's score when the enemy dies.
public AudioClip deathClip; // The sound to play when the enemy dies.
Animator anim; // Reference to the animator.
AudioSource enemyAudio; // Reference to the audio source.
ParticleSystem hitParticles; // Reference to the particle system that plays when the enemy is damaged.
CapsuleCollider capsuleCollider; // Reference to the capsule collider.
bool isSinking; // Whether the enemy has started sinking through the floor.
void Awake ()
{
// Setting up the references.
anim = GetComponent <Animator> ();
enemyAudio = GetComponent <AudioSource> ();
hitParticles = GetComponentInChildren <ParticleSystem> ();
capsuleCollider = GetComponent <CapsuleCollider> ();
// Setting the current health when the enemy first spawns.
currentHealth = startingHealth;
}
void Update ()
{
// If the enemy should be sinking...
if(isSinking)
{
// ... move the enemy down by the sinkSpeed per second.
transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
}
}
public void TakeDamage (int amount, Vector3 hitPoint)
{
// If the enemy is dead...
if(isDead)
// ... no need to take damage so exit the function.
return;
// Play the hurt sound effect.
enemyAudio.Play ();
// Reduce the current health by the amount of damage sustained.
currentHealth -= amount;
// Set the position of the particle system to where the hit was sustained.
hitParticles.transform.position = hitPoint;
// And play the particles.
hitParticles.Play();
// If the current health is less than or equal to zero...
if(currentHealth <= 0)
{
// ... the enemy is dead.
Death ();
}
}
void Death ()
{
// The enemy is dead.
isDead = true;
// Turn the collider into a trigger so shots can pass through it.
capsuleCollider.isTrigger = true;
deathCount++;
Debug.Log("Deaths" + deathCount);
// Tell the animator that the enemy is dead.
anim.SetTrigger ("Dead");
// Change the audio clip of the audio source to the death clip and play it (this will stop the hurt clip playing).
enemyAudio.clip = deathClip;
enemyAudio.Play ();
}
public void StartSinking ()
{
// Find and disable the Nav Mesh Agent.
GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
// Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
GetComponent <Rigidbody> ().isKinematic = true;
// The enemy should no sink.
isSinking = true;
// Increase the score by the enemy's score value.
ScoreManager.score += scoreValue;
// After 2 seconds destory the enemy.
Destroy (gameObject, 2f);
}
}
}
all of the 3 enemies in the game have this script attached on their prefabs so they behave in the same way, so I cannot see why the counter will not increment when an enemy is destroyed.
when debugging the counter seems to go to 1 and then every kill after that just stays at 1 again.
that is correct. It's a member, so it will existing for each instance of your enemy. You want to track three different healths, right?
So enemy 1 start with 100, enemy 2 with 100, enemy 3 with 100. When enemy 1 gets 20 damage, it goes to 80 and 2,3 stay at 100, right? Why would the counter behave differently then? They all start at 0 and go to 1 when they die.
Either have an upper object (e.g. enemymanager) and have that count the times an enemy die (preferred solution) or use a static variable.
Related
I'm trying to use encoders to track the movement of three wheels on a robot, but as soon as any of the motors move the robot "locks up", it stops responding to commands, stops printing to the serial monitor, and just keeps spinning its wheels until I turn it off. I cut out everything except just the code to track one encoder and tried turning the wheel by hand to sus out the problem, but it still locked up. And even more strangely, now it will start spinning one of the wheels even though I've removed any code that should have it do that, even by mistake.
I used the Arduino IDE to program the pico since I've got no familiarity with python, but I can't find any information or troubleshooting tips for using interrupts with the pico that don't assume you're using micropython.
Here's the simplified code I'm using to try to find the problem. All it's meant to do is keep track of how many steps the encoder has made and print that to the serial monitor every second. Ive tried removing the serial and having it light up LEDs instead but that didn't help.
int encA = 10;
int encB = 11;
int count = 0;
int timer = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(encA),readEncoder,RISING);
timer = millis();
}
void loop() {
// put your main code here, to run repeatedly:
if (timer - millis() > 5000) {
Serial.println(count);
timer = millis();
}
}
void readEncoder() {
int bVal = digitalRead(encB);
if (bVal == 0) {
count--;
}
else{
count++;
}
}
Does the mapping function digitalPinToInterrupt for the Pi Pico work?
Can you try just using the interrupt number that corresponds to the pi?
attachInterrupt(9,readEncoder,RISING); //Or the number 0-25 which maps to that pin
https://raspberrypi.github.io/pico-sdk-doxygen/group__hardware__irq.html
You have the wrong pin to encoder in your example (maybe you incorrectly copy and pasted)?
attachInterrupt(digitalPinToInterrupt(**encA**),readEncoder,RISING);
void readEncoder() {
int bVal = digitalRead(**encB**); ...}
There is similar code on GitHub that you could modify and try instead.
https://github.com/jumejume1/Arduino/blob/master/ROTARY_ENCODER/ROTARY_ENCODER.ino
It might help you find a solution.
Also,
https://www.arduino.cc/reference/en/libraries/rpi_pico_timerinterrupt/
The interrupt number corresponds to the pin (unless you have reassigned it or disabled it) so for pin 11 the code can be:
attachInterrupt(11, buttonPressed, RISING);
This works:
bool buttonPress = false;
unsigned long buttonTime = 0; // To prevent debounce
void setup() {
Serial.begin(9600);
pinMode(11, INPUT_PULLUP);
attachInterrupt(11, buttonPressed, RISING);
// can be CHANGE or LOW or RISING or FALLING or HIGH
}
void loop() {
if(buttonPress) {
Serial.println(F("Pressed"));
buttonPress= false;
} else {
Serial.println(F("Normal"));
}
delay(250);
}
void buttonPressed() {
//Set timer to work for your loop code time
if (millis() - buttonTime > 250) {
//button press ok
buttonPress= true;
}
buttonTime = millis();
}
See: https://raspberrypi.github.io/pico-sdk-doxygen/group__hardware__irq.html for disable, enable etc.
In the code below, i want the balls to change from ArrayList ballList to another ArrayList oldBalls as soon as their age turns higher than a threshold value.
This code should be very simple but i can't figure out why when the age is same as the threshold (not larger) they disappear and then they come back 2 frames later.
I have checked related questions using iterators for ArrayLists in java but i think there should be a way to do this in processing without java.
Also i cant seem to post any question on the processing forum even though i can sign in, no idea why...
I have reduced the code to the minimum able to reproduce the error.
ArrayList <Ball> ballList;
ArrayList <Ball> oldBalls;
int threshold=4;
PFont font;
void setup(){
size(400,400);
frameRate(0.5);
font=createFont("Georgia", 18);
textFont(font);
textAlign(CENTER, CENTER);
ballList=new ArrayList<Ball>();
oldBalls=new ArrayList<Ball>();
noFill();
strokeWeight(2);
}
void draw(){
background(0);
Ball b=new Ball(new PVector(10, random(height/10,9*height/10)),new PVector(10,0),0);
ballList.add(b);
stroke(0,0,200);
for(int i=0;i<oldBalls.size();i++){
Ball bb=oldBalls.get(i);
bb.update();
bb.render();
text(bb.age,bb.pos.x,bb.pos.y);
}
stroke(200,0,0);
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
}
class Ball{
PVector pos;
PVector vel;
int age;
Ball(PVector _pos, PVector _vel, int _age){
pos=_pos;
vel=_vel;
age=_age;
}
void migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
}
}
void update(){
pos.add(vel);
age+=1;
}
void render(){
ellipse(pos.x,pos.y,24,24);
}
}
Note how balls labelled with age=threshold suddenly disappear...
i guess the problem is here:
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
//add this
if(bb.migrate())
i--;
text(bb.age,bb.pos.x,bb.pos.y);
}
and
boolean migrate(){
if(age>threshold){
oldBalls.add(this);
ballList.remove(this);
//and this
return true;
}
return false;
}
migrate() will remove the object from the ballList and reduce it's size by 1.
What it looks like is happening here is because you're altering the List's whilst iterating through them. Consider this for loop you have here
for(int i=0;i<ballList.size();i++){
Ball bb=ballList.get(i);
bb.update();
bb.render();
bb.migrate();
text(bb.age,bb.pos.x,bb.pos.y);
}
Say ballList has 2 balls in it both age 3, the first loops gets ball[0] and then removes it from the list, i will increment and the loop will immediately exit because ballList.size() is now 1. So it's not the ball which gets to age 4 that vanishes but the subsequent one.
I've been reading various tutorials on how to write a contact listener, and I can't wrap my head around it.
Here is what I have so far:
In each of the classes that I have representing a physics object I do:
_body->SetUserData(self);
I write a contact listener class containing the following two methods:
void ContactListener::BeginContact(b2Contact* contact)
{
// Box2d objects that collided
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
// Sprites that collided
MyNode* actorA = (MyNode*) fixtureA->GetBody()->GetUserData();
MyNode* actorB = (MyNode*) fixtureB->GetBody()->GetUserData();
}
void ContactListener::EndContact(b2Contact* contact)
{
// Box2d objects that collided
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
// Sprites that collided
MyNode* actorA = (MyNode*) fixtureA->GetBody()->GetUserData();
MyNode* actorB = (MyNode*) fixtureB->GetBody()->GetUserData();
}
I don't know what to do next. I now have the two sprites which are colliding, but I want to do the following:
1) When they collide, I want to remove one of the sprites from the world, based on the type of object. (for example if one a cat object and the other is a mouse object, I want to remove the mouse object.
2) I want to let the cat object know it ate a mouse
3) I want the cat to continue moving as if it didn't contact with the mouse.
4) I still wan't the cat to collide normally with things like the terrain.
What do I do next ? I'm pretty clueless on what to do? How do I get the cat to continue to collide normally with the terrain, but not with the mouse? When do I remove the mouse?
Having an "Entity" class that hold the reference to the Box2D body and does the manipulations on it is definitely a good way to go. If you have a Spaceship class vs. a Meteor class, each of them can supply their own derived methods of controlling the body (AI), but each of them has common logic and code to support operations on "Things that have a body" (e.g. common "Entity" base class). I think you are on the right track.
It gets a little murky when the contacts start happening. This is where you start getting into the architecture of your overall system, not just the structure of the physics world or a single Coco2d Scene.
Here is how I have done this in the past:
First I set up the contact listener, listed below:
class EntityContactListener : public ContactListener
{
private:
GameWorld* _gameWorld;
EntityContactListener() {}
typedef struct
{
Entity* entA;
Entity* entB;
} CONTACT_PAIR_T;
vector<CONTACT_PAIR_T> _contactPairs;
public:
virtual ~EntityContactListener() {}
EntityContactListener(GameWorld* gameWorld) :
_gameWorld(gameWorld)
{
_contactPairs.reserve(128);
}
void NotifyCollisions()
{
Message* msg;
MessageManager& mm = GameManager::Instance().GetMessageMgr();
for(uint32 idx = 0; idx < _contactPairs.size(); idx++)
{
Entity* entA = _contactPairs[idx].entA;
Entity* entB = _contactPairs[idx].entB;
//DebugLogCPP("Contact Notification %s<->%s",entA->ToString().c_str(),entB->ToString().c_str());
msg = mm.CreateMessage();
msg->Init(entA->GetID(), entB->GetID(), Message::MESSAGE_COLLISION);
mm.EnqueueMessge(msg, 0);
msg = mm.CreateMessage();
msg->Init(entB->GetID(), entA->GetID(), Message::MESSAGE_COLLISION);
mm.EnqueueMessge(msg, 0);
}
_contactPairs.clear();
}
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
b2Fixture* fixtureA = contact->GetFixtureA();
b2Body* bodyA = fixtureA->GetBody();
Entity* entityA = bodyA->GetUserData();
b2Fixture* fixtureB = contact->GetFixtureB();
b2Body* bodyB = fixtureB->GetBody();
Entity* entityB = bodyB->GetUserData();
if(test if entityA and entityB should not have collision response)
{
contact->SetEnabled(false);
}
// Do this if you want there to be collision notification, even if
// there is no response.
AddContactPair(entA,entB);
}
void AddContactPair(Entity* entA, Entity* entB)
{
for(uint32 idx = 0; idx < _contactPairs.size(); idx++)
{
if(_contactPairs[idx].entA == entA && _contactPairs[idx].entB == entB)
return;
// Not sure if this is needed...
if(_contactPairs[idx].entA == entB && _contactPairs[idx].entA == entB)
return;
}
CONTACT_PAIR_T pair;
pair.entA = entA;
pair.entB = entB;
_contactPairs.push_back(pair);
}
// BEWARE: You may get multiple calls for the same event.
void BeginContact(b2Contact* contact)
{
Entity* entA = (Entity*)contact->GetFixtureA()->GetBody()->GetUserData();
Entity* entB = (Entity*)contact->GetFixtureB()->GetBody()->GetUserData();
assert(entA != NULL);
assert(entB != NULL);
// Not sure this is still needed if you add it in the pre-solve.
// May not be necessary...
AddContactPair(entA, entB);
}
// BEWARE: You may get multiple calls for the same event.
void EndContact(b2Contact* contact)
{
}
};
Because of the way the engine works, you can get multiple contact hits for the same bodies. This listener filters them so if two Entities collide, you only get one message.
The Listener only stores the collisions that have occurred. It could be modified to further separate them into "begins" and "ends" for other purposes. Here, contact meant "you've been hit by something". I didn't need to know if it stopped contacting.
The call to NotifyCollisions is the "secret sauce". It sends out a message to both the contacted entities (via a message system) that they hit something and the other Entity is what they hit. Bullet hit ship. Bullet destroys self. Ship damages self based on bullet properties (GetDamageInflicted() method). This in turn signals the graphics system to remove the bullet from the display. If the ship was destroyed, it is destroyed as well.
From an overall execution standpoint:
Before you begin, assign the contact listener.
Each Cycle of your game:
Call "Update" on all your Entities. This updates their physics forces, etc.
Update Box2d world.
Call NotifyCollisions on Listener.
Remove dead Entities from system.
Was this helpful?
I'm using Cocos2d iPhone with Box2D to create a basic physics engine.
Occasionally the user is required to drag around a small box2D object.
Creation of touchjoints on small objects is a bit hit and miss, with the game engine seeing it as a tap on blank space as often as actually creating the appropriate touchjoint. In practice this means the user is constantly mashing their fingers against the screen in vain attempts to move a stubborn object. I want the game to select small objects easily without this 'hit and miss' effect.
I could create the small objects with larger sensors around them, but this is not ideal because objects above a certain size (around 40px diameter) don't need this extra layer of complexity; and the small objects are simply the big objects scaled down to size.
What are some strategies I could use to allow the user experience to be better when moving small objects?
Here's the AABB code in ccTouchBegan:
b2Vec2 locationWorld = b2Vec2(touchLocation.x/PTM_RATIO, touchLocation.y/PTM_RATIO);
b2AABB aabb;
b2Vec2 delta = b2Vec2(1.0/PTM_RATIO, 1.0/PTM_RATIO);
//Changing the 1.0 here to a larger value doesn't make any noticeable difference.
aabb.lowerBound = locationWorld - delta;
aabb.upperBound = locationWorld + delta;
SimpleQueryCallback callback(locationWorld);
world->QueryAABB(&callback, aabb);
if(callback.fixtureFound){
//dragging code, updating sprite location etc.
}
SimpleQueryCallback code:
class SimpleQueryCallback : public b2QueryCallback
{
public:
b2Vec2 pointToTest;
b2Fixture * fixtureFound;
SimpleQueryCallback(const b2Vec2& point) {
pointToTest = point;
fixtureFound = NULL;
}
bool ReportFixture(b2Fixture* fixture) {
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody) {
if (fixture->TestPoint(pointToTest)) {
fixtureFound = fixture;
return false;
}
}
return true;
}
};
What about a minimum collision box for touches? Objects with less than 40px diameter use the 40px diameter, all larger objects use their actual diameter.
What I ended up doing - thanks to iforce2d, was change ReportFixture in SimpileQueryCallback to:
bool ReportFixture(b2Fixture* fixture) {
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody) {
//if (fixture->TestPoint(pointToTest)) {
fixtureFound = fixture;
return true;
//}
}
return true;
}
And increase the delta to 10.0/PTM_RATIO.
Edit: With enough rewriting, and commenting, I have it running, will post final below for others.
Edit2: I've been more updating my own version, and I've learned the original coder was not very good with C++, you may want to go over everything in there before using it, check out comments below post
The currently available CCScrollView for cocos2d-x suffers from one major flaw: It's messed up.
Specifically, the cpp function headers do not match the .h file's.
The cpp file refers to UIEvent and NSMutableArray, not X-Platform.
The scroll view itself must have an array added, which limits your ability to use a for loop to create your menu items (if creating menu items), since you can't use a mutable one, and they don't subclass each other like iOS so you can't just use a mutable then say CCArray * array = mutable->getMutableArray() or similar.
Also, the defines are outdated (though fixable through adding the CCX_SAFE_DELETE via the translation rules on the cocos2d-x site), and a variety of random templates trying to create NS and UI objects that are not even within the project for I have no clue why.
The basic idea is, aside from the addition of using mutable arrays, this class is way too messed up to bother translating to C++. I don't believe the author compiled the version he has up, as the headers don't match. I thought I downloaded both (there's 2 of each) the cpp and .h files, and both have UIEvent instead of CC along with the other issues.
Note: I have fixed a variety of the above, and changed SelectorProtocol to CCObject in various places, but it's just getting overwhelming.
Perhaps I should use the Parallax node instead?
This is just ridiculous, perhaps it's great for Cocos2d but it's not working on c2d-X. Anyway, I'll be recoding and searching, thanks for any suggestions!
Edit: Here's the classes I'm now using. Not done editing, but these will get anyone started, and compiling on more than just iPhone
Header:
#ifndef __CCSCROLLLAYER__
#define __CCSCROLLLAYER__
// CCScrollLayer.h
//
// Copyright 2010 DK101
// http://dk101.net/2010/11/30/implementing-page-scrolling-in-cocos2d/
//
// Copyright 2010 Giv Parvaneh.
// http://www.givp.org/blog/2010/12/30/scrolling-menus-in-cocos2d/
//
// Copyright 2011 Stepan Generalov
//
// Copyright 2011 Eli Yukelzon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Original source: https://github.com/cocos2d/cocos2d-iphone-extensions/tree/master/Extensions/CCScrollLayer
// Last updated: October 1, 2011
#include "cocos2d.h"
namespace cocos2d {
class CCScrollLayer;
class CCScrollLayerDelegate
{
public:
/** Called when scroll layer begins scrolling.
* Usefull to cancel CCTouchDispatcher standardDelegates.
*/
virtual void scrollLayerScrollingStarted(CCScrollLayer* sender) {}
/** Called at the end of moveToPage:
* Doesn't get called in selectPage:
*/
virtual void scrollLayerScrolledToPageNumber(CCScrollLayer* sender, unsigned int page) {}
};
/*
It is a very clean and elegant subclass of CCLayer that lets you pass-in an array
of layers and it will then create a smooth scroller.
Complete with the "snapping" effect. You can create screens with anything that can be added to a CCLayer.
*/
class CCScrollLayer : public CCLayer
{
int currentScreen; //added
int totalScreens;
float scrollWidth;
float scrollHeight;
float startWidth;
float startHeight;
int startSwipe;
public:
//CCScrollLayer();
~CCScrollLayer();
static CCScrollLayer* nodeWithLayers(CCArray* layers, int widthOffset);
bool initWithLayers(CCArray* layers, int widthOffset);
/** Updates all pages positions & adds them as children if needed.
* Can be used to update position of pages after screen reshape, or
* for update after dynamic page add/remove.
*/
void updatePages();
/** Adds new page and reorders pages trying to set given number for newly added page.
* If number > pages count - adds new page to the right end of the scroll layer.
* If number <= 0 - adds new page to the left end of the scroll layer.
* #attention Designated addPage method.
*/
void addPage(CCLayer* aPage, unsigned int pageNumber);
/** Adds new page to the right end of the scroll layer. */
void addPage(CCLayer* aPage);
/** Removes page if it's one of scroll layers pages (not children)
* Does nothing if page not found.
*/
void removePage(CCLayer* aPage);
/** Removes page with given number. Doesn nothing if there's no page for such number. */
void removePageWithNumber(unsigned int pageNumber);
/* Moves scrollLayer to page with given number & invokes delegate
* method scrollLayer:scrolledToPageNumber: at the end of CCMoveTo action.
* Does nothing if number >= totalScreens or < 0.
*/
void moveToPage(unsigned int pageNumber);
/* Immedeatly moves scrollLayer to page with given number without running CCMoveTo.
* Does nothing if number >= totalScreens or < 0.
*/
void selectPage(unsigned int pageNumber);
CC_SYNTHESIZE(CCScrollLayerDelegate*, m_pDelegate, Delegate);
/** Calibration property. Minimum moving touch length that is enough
* to cancel menu items and start scrolling a layer.
*/
CC_SYNTHESIZE(CGFloat, m_fMinimumTouchLengthToSlide, MinimumTouchLengthToSlide);
/** Calibration property. Minimum moving touch length that is enough to change
* the page, without snapping back to the previous selected page.
*/
CC_SYNTHESIZE(CGFloat, m_fMinimumTouchLengthToChangePage, MinimumTouchLengthToChangePage);
/** If YES - when starting scrolling CCScrollLayer will claim touches, that are
* already claimed by others targetedTouchDelegates by calling CCTouchDispatcher#touchesCancelled
* Usefull to have ability to scroll with touch above menus in pages.
* If NO - scrolling will start, but no touches will be cancelled.
* Default is YES.
*/
CC_SYNTHESIZE(bool, m_bStealTouches, StealTouches);
/** Whenever show or not white/grey dots under the scroll layer.
* If yes - dots will be rendered in parents transform (rendered after scroller visit).
*/
CC_SYNTHESIZE(bool, m_bShowPagesIndicator, ShowPagesIndicator);
/** Position of dots center in parent coordinates.
* (Default value is screenWidth/2, screenHeight/4)
*/
CC_SYNTHESIZE_PASS_BY_REF(CCPoint, m_tPagesIndicatorPosition, PagesIndicatorPosition);
/** Total pages available in scrollLayer. */
unsigned int getTotalScreens() const;
/** Current page number, that is shown. Belongs to the [0, totalScreen] interval. */
CC_SYNTHESIZE_READONLY(unsigned int, m_uCurrentScreen, CurrentScreen);
/** Offset, that can be used to let user see next/previous page. */
CC_SYNTHESIZE(CGFloat, m_fPagesWidthOffset, PagesWidthOffset);
/** Offset that can be used to let user see empty space over first or last page. */
CC_SYNTHESIZE(CGFloat, m_fMarginOffset, MarginOffset);
/** Array of pages CCLayer's */
CC_SYNTHESIZE_READONLY(CCArray*, m_pLayers, Pages);
protected:
// The x coord of initial point the user starts their swipe.
CGFloat m_fStartSwipe;
// Internal state of scrollLayer (scrolling or idle).
int m_iState;
bool m_bStealingTouchInProgress;
// Holds the touch that started the scroll
CCTouch* m_pScrollTouch;
//void visit();
//void moveToPageEnded();
unsigned int pageNumberForPosition(const CCPoint& position);
CCPoint positionForPageWithNumber(unsigned int pageNumber);
void claimTouch(CCTouch* pTouch);
void cancelAndStoleTouch(CCTouch* pTouch, CCEvent* pEvent);
//void registerWithTouchDispatcher();
bool ccTouchBegan(CCTouch* pTouch, CCEvent* pEvent);
void ccTouchMoved(CCTouch* pTouch, CCEvent* pEvent);
void ccTouchEnded(CCTouch* pTouch, CCEvent* pEvent);
//void ccTouchCancelled(CCTouch* pTouch, CCEvent* pEvent);
};
} //end namespace
#endif
CPP
// CCScrollLayer.cpp
// Museum
//
// Created by GParvaneh on 29/12/2010.
// Copyright 2010. All rights reserved.
// Ported to C++ by Lior Tamam on 03/04/2011
#include "CCScrollLayer.h"
using namespace cocos2d;
CCScrollLayer* CCScrollLayer::nodeWithLayers(CCArray* layers, int widthOffset)
{
CCScrollLayer *pRet = new CCScrollLayer();
if (pRet && pRet->initWithLayers(layers, widthOffset))
{
pRet->autorelease();
return pRet;
}
CCX_SAFE_DELETE(pRet);
return NULL;
}
bool CCScrollLayer::initWithLayers(CCArray* layers, int widthOffset)
{
if (CCLayer::init())
{
// Make sure the layer accepts touches
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true);
// Set up the starting variables
//if(!widthOffset)
{
// widthOffset = 0;
}
currentScreen = 1;
// offset added to show preview of next/previous screens
scrollWidth = (int)CCDirector::sharedDirector()->getWinSize().width - widthOffset;
scrollHeight = (int)CCDirector::sharedDirector()->getWinSize().height;
startWidth = scrollWidth;
startHeight = scrollHeight;
// Loop through the array and add the screens
unsigned int i;
for (i=0; i<layers->count(); i++)
{
CCLayer* l = (CCLayer*)layers->objectAtIndex(i);
//l->setAnchorPoint(ccp(0,0));
//l->setPosition(ccp((i*scrollWidth),0));
addChild(l);
}
// Setup a count of the available screens
totalScreens = layers->count();
return true;
}
else
{
return false;
}
}
void CCScrollLayer::setMaximumScrollHeight(float maxHeight)
{
//Make the offset match expected pixels (include the current screen if at ccp(0,0)
maxHeight -= CCDirector::sharedDirector()->getWinSize().height;
maximumScrollHeight = maxHeight;
}
CCScrollLayer::~CCScrollLayer()
{
CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
CCLayer::onExit();
}
bool CCScrollLayer::ccTouchBegan(CCTouch *touch, CCEvent *withEvent)
{
//
// CCPoint touchPoint = touch->locationInView();
// touchPoint = CCDirector::sharedDirector()->convertToGL(touchPoint);
//
// startSwipe = (int)touchPoint.y;
return true;
}
void CCScrollLayer::ccTouchMoved(CCTouch *touch, CCEvent *withEvent)
{
CCPoint touchPoint = touch->locationInView();
CCPoint prevPoint = touch->previousLocationInView();
touchPoint = CCDirector::sharedDirector()->convertToGL(touchPoint);
prevPoint = CCDirector::sharedDirector()->convertToGL(prevPoint);
CCPoint difference = ccp( touchPoint.x - prevPoint.x , touchPoint.y - prevPoint.y);
CCPoint currentPos = this->getPosition();
currentPos = ccp( currentPos.x, currentPos.y+difference.y);
if (currentPos.y > maximumScrollHeight)
{
currentPos.y = maximumScrollHeight;
//this->setPositionY(maximumScrollHeight);
}
else if (currentPos.y < 0)
{
currentPos.y = 0;
// this->setPositionY(0);
}
this->setPosition(currentPos);
}
/*
void CCScrollLayer::ccTouchEnded(CCTouch *touch, CCEvent *withEvent)
{
//CCPoint touchPoint = touch->locationInView();
//touchPoint = CCDirector::sharedDirector()->convertToGL(touchPoint);
int newX = (int)touchPoint.x;
if ( (newX - startSwipe) < -scrollWidth / 3 && (currentScreen+1) <= totalScreens )
{
// this->moveToNextPage();
}
else if ( (newX - startSwipe) > scrollWidth / 3 && (currentScreen-1) > 0 )
{
// this->moveToPreviousPage();
}
else
{
// this->moveToPage(currentScreen);
}
}
*/
Reviving an old thread to add new information, for anyone who found this through a search engine: CCScrollView is now part of the GUI extension and seems to work fairly well. There should be no more need for the implementations referenced above.
Check out the forums on Cocos2d-x's site for the latest one. They're being reworked right now by the author based on this.
http://www.cocos2d-x.org/boards/18/topics/1090?r=10835#message-10835