Sprite not animating - animation

I wrote two classes; Animation, and Actor. For some reason, the sprite image doesn't change. It stays the first frame the entire time. The code is fine I have no issues compiling, my logic is just wrong somewhere and it isn't acting how I expected it to.
Animation class declaration:
class Animation
{
public:
Animation(std::string path, int frames);
~Animation();
void nextFrame();
void gotoStart();
bool loadFrames();
sf::Texture& getActiveFrame();
private:
int frameCount;
std::string pathToAnimation;
int currentFrame;
sf::Texture frame[];
};
Animation class implementation:
Animation::Animation(std::string path, int frames)
{
pathToAnimation = path;
frameCount = frames;
}
Animation::~Animation()
{
// destructor
}
void Animation::nextFrame()
{
if(currentFrame < frameCount)
{
currentFrame = 1;
}
else
currentFrame += 1;
}
void Animation::gotoStart()
{
currentFrame = 1;
}
bool Animation::loadFrames()
{
for(int i = 01; i < frameCount; i++)
{
if(!frame[i].loadFromFile(pathToAnimation + std::to_string(i) + ".jpg")) return false;
}
return true;
}
sf::Texture& Animation::getActiveFrame()
{
return frame[currentFrame];
}
Actor class declaration:
class Actor
{
public:
Actor();
~Actor();
void setActiveAnimation(std::shared_ptr<MaJR::Animation> anim);
void draw(sf::RenderWindow& win);
private:
sf::Sprite sprite;
std::shared_ptr<MaJR::Animation> activeAnimation;
};
Actor class implementation:
Actor::Actor()
{
// constructor
}
Actor::~Actor()
{
// destructor
}
void Actor::setActiveAnimation(std::shared_ptr<MaJR::Animation> anim)
{
activeAnimation = anim;
activeAnimation->gotoStart();
}
void Actor::draw(sf::RenderWindow& win)
{
sprite.setTexture(activeAnimation->getActiveFrame());
win.draw(sprite);
activeAnimation->nextFrame();
}
Here's the code to test it:
int main()
{
sf::RenderWindow Window(sf::VideoMode(800, 600), "MaJR Game Engine Sandbox");
std::shared_ptr<MaJR::Animation> DroneStandNorth = std::make_shared<MaJR::Animation>("./Assets/Sprites/Zerg/Units/Drone/Stand/North/", 61);
if(!DroneStandNorth->loadFrames()) return EXIT_FAILURE;
MaJR::Actor Drone;
Drone.setActiveAnimation(DroneStandNorth);
while(Window.isOpen())
{
sf::Event Event;
while(Window.pollEvent(Event))
{
if(Event.type == sf::Event::Closed)
Window.close();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
Window.close();
Window.clear();
Drone.draw(Window);
Window.display();
}
return 0;
}
I'm at a complete loss as to what's wrong here. If you want to compile everything yourself, here's the original files: http://www.filedropper.com/animationtesttar be sure to use -std=c++0x or whatever you have to do to use C++11 with your compiler.

In your animation implementation, you have:
void Animation::nextFrame()
{
if(currentFrame < frameCount)
{
currentFrame = 1;
}
else
currentFrame += 1;
}
Since the currentFrame starts at 1, it will always be less than frameCount, so it will always be set to 1. Change to:
void Animation::nextFrame()
{
if(currentFrame >= frameCount)
{
currentFrame = 1;
}
else
currentFrame += 1;
}
This way, when the currentFrame equals frameCount (in your test case 61), it will be reset. Since nextFrame() gets called after the Actor's Draw(), the last frame will be drawn and then the currentFrame will be reset back to 1.

Related

Why won't image 1 move to the right?

I'm very new to coding and was wondering how I could make this image move to the right. I added all of my code so that it would be a bit more understandable for what's going on. The moveRight command will not actually move the png to the right which is why I need help fixing and understanding why it won't work. If someone can please help me it would be greatly appreciated.
PImage background, backgroundGameState1, headbasketballbackground, player1, player2;
boolean moveRight, moveLeft;
int canvasSizeX= 1000;
int canvasSizeY = 600;
int mainBackgroundX = 1000;
int mainBackgroundY = 600;
int gameState1 = 1;
int player1X = 100;
int player1Y = 200;
int player2X = 100;
int player2Y = 200;
int backgroundGameState1X= 1000;
int backgroundGameState1Y=600;
int time;
int player1MovmentX = 100;
int player2MovmentX = 700;
void setup() {
//size of canvas
size(1000, 600);
//Loaded images and called them, also made sure to resize them in order to match the canvas size or to make program more asthetically pleasing
background = loadImage("headbasketballbackground.png");
background.resize(mainBackgroundX, mainBackgroundY);
backgroundGameState1 = loadImage("backgroundgamestate1.png");
backgroundGameState1.resize(backgroundGameState1X, backgroundGameState1Y);
player1 = loadImage("steph.png");
player1.resize(player1X, player1Y);
player2 = loadImage("paul.png");
player2.resize(player2X, player2Y);
time=millis();
}
void draw() {
if (gameState1 == 1) {
background(backgroundGameState1);
if (millis() > time + 1000) {
text("Click On Space To Enter The Game!", 100, 100);
textSize(50);
// delay(3000);
}
drawGameState1();
}
if (gameState1 == 2) {
background(background);
image(player1, player1MovmentX, 300);
image(player2, player2MovmentX, 300);
}
// if (gameState2 == 3) {
// text("Congrats you won!");
//}
}
void drawGameState1() {
}
void drawGameState2() {
drawPlayer1Movment();
}
void drawPlayer1Movment(){
if(moveRight){
player1MovmentX += 25;
}
}
void drawGameState3() {
}
void keyPressed() {
if (gameState1 == 1) {
if (keyCode == 32) {
gameState1 = 2;
}
}
else if(gameState1 == 2){
if(keyCode == RIGHT){
moveRight = true;
}
}
}
void keyReleased(){
if(keyCode == RIGHT){
moveRight = false;
}
}
I don't think you ever called drawPlayer1Movement(). Add it to keyPressed() and player1 should move to the right when you hit the right arrow.
void keyPressed() {
if (gameState1 == 1) {
if (keyCode == 32) {
gameState1 = 2;
}
} else if (gameState1 == 2) {
if (keyCode == RIGHT) {
moveRight = true;
drawPlayer1Movment();
}
}
}

How to change cells of array by keyPressed()?

I try to make a web application.
You can change cells of the array by pressing arrow keys here.
There is a class "Module" with methods display() and update(). These methods change the inner array data[].
class Module {
int i; // index
int x; // coordinate
int y; // coordinate
int[] data = new int[]{0,0,0,0,0};
// Contructor
Module(int x){
this.x = x;
}
void update() {
data[i]=_mas_stor;
}
void display(){
text(data[i], x, 100);
}
}
But how to set the initial value of the array _mass[] at the beginning of the program?
The whole program here.
There is no need of an array of data in the class Module. It is sufficient that each object has it single data member. Wirte a constructor, eher you can pass to the initial data (Module(int x, int d)):
class Module {
int i;
int x;
int y;
int data;
// Contructor
Module(int x, int d){
this.x = x;
this.data = d;
}
void update() {
data=_mas[global_i];
}
void display(){
textSize(30);
text(data, x, 100);
}
}
Now the object can be initialized in a loop with ease:
int[] _mas ={1,2,3,4,5};
int global_i = 0;
Module [] mods;
void setup() {
size(500, 400);
mods = new Module[5];
for (int i = 0; i < 5; ++ i ) {
mods[i] = new Module(i*50+50, _mas[i]);
}
}
Further you have to ensure that global_i doesn't go out of bounds in keyPressed:
void keyPressed() {
if (keyCode == UP) {
_mas[global_i]++;
}
if (keyCode == DOWN) {
_mas[global_i]--;
}
if (keyCode == LEFT) {
global_i--;
if (global_i < 0)
global_i = 4;
}
if (keyCode == RIGHT) {
global_i++;
if (global_i > 4)
global_i = 0;
}
}
Note, you can further improve you program, if you skip the global variable _mas and add a increment method (inc) and decrement method (dec) to the class Module, instead of the update method:
int global_i = 0;
Module [] mods;
void setup() {
size(500, 400);
mods = new Module[5];
for (int i = 0; i < 5; ++ i ) {
mods[i] = new Module(i*50+50, i);
}
}
void draw() {
background(50);
for (int i = 0; i < 5; ++ i ) {
mods[i].display();
}
}
void keyPressed() {
if (keyCode == UP) {
println("up");
mods[global_i].inc();
}
if (keyCode == DOWN) {
mods[global_i].dec();
}
if (keyCode == LEFT) {
global_i--;
if (global_i < 0)
global_i = 4;
}
if (keyCode == RIGHT) {
global_i++;
if (global_i > 4)
global_i = 0;
}
}
class Module {
int i;
int x;
int y;
int data;
// Contructor
Module(int x, int d){
this.x = x;
this.data = d;
}
void inc() {
this.data ++;
}
void dec() {
this.data --;
}
void display(){
textSize(30);
text(data, x, 100);
}
}
You usually set the initial value of an array using a for loop. Something like this:
String myArray = new String[10];
for(int i = 0; i < myArray.length; i++){
myArray[i] = "hello world";
}
What you put inside the for loop depends on what values you want your array to start with.

Processing: Multiple bullets in top down shooter

I am trying to make a simple top down shooter. When the user presses W, A, S or D a 'bullet' (rectangle) will come out of the 'shooter'. With my code, you can only shoot one bullet per direction until it reaches the end of the screen. Is there a way to make it so they (the user) can shoot multiple bullets in one direction?
Here's my code:
package topdownshooter;
import processing.core.PApplet;
import processing.core.PImage;
public class TopDownShooter extends PApplet {
PImage shooter;
float shooterX = 400;
float shooterY = 300;
float u_bulletSpeed;
float l_bulletSpeed;
float d_bulletSpeed;
float r_bulletSpeed;
boolean shootUp = false;
boolean shootLeft = false;
boolean shootDown = false;
boolean shootRight = false;
public static void main(String[] args) {
PApplet.main("topdownshooter.TopDownShooter");
}
public void setup() {
shooter = loadImage("shooter.png");
}
public void settings() {
size(800, 600);
}
public void keyPressed() {
if(key == 'w') {
shootUp = true;
}
if(key == 'a') {
shootLeft = true;
}
if(key == 's') {
shootDown = true;
}
if(key == 'd') {
shootRight = true;
}
}
public void draw() {
background(206);
imageMode(CENTER);
image(shooter, shooterX, shooterY);
if(shootUp == true) {
rect(shooterX, shooterY-u_bulletSpeed, 5, 5);
u_bulletSpeed += 2;
if(u_bulletSpeed > 300) {
u_bulletSpeed = 0;
shootUp = false;
}
}
if(shootLeft == true) {
rect(shooterX-l_bulletSpeed, shooterY, 5, 5);
l_bulletSpeed += 2;
if(l_bulletSpeed > 400) {
l_bulletSpeed = 0;
shootLeft = false;
}
}
if(shootDown == true) {
rect(shooterX, shooterY+d_bulletSpeed, 5, 5);
d_bulletSpeed += 2;
if(d_bulletSpeed > 300) {
d_bulletSpeed = 0;
shootDown = false;
}
}
if(shootRight == true) {
rect(shooterX+r_bulletSpeed, shooterY, 5, 5);
r_bulletSpeed += 2;
if(r_bulletSpeed > 400) {
r_bulletSpeed = 0;
shootRight = false;
}
}
}
}
The language is processing and I am using the eclipse IDE.
Thanks!
Here's what I would do if I were you. First I'd encapsulate your bullet data into a class, like this:
class Bullet{
float x;
float y;
float xSpeed;
float ySpeed;
// you probably want a constructor here
void drawBullet(){
// bullet drawing code
}
}
Then I'd create an ArrayList that holds Bullet instances:
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
To add a bullet, I'd create a new instance and add it to the ArrayList like this:
bullets.add(new Bullet(bulletX, bulletY));
Then to draw the bullets, I'd iterate over the ArrayList and call the corresponding function:
for(Bullet b : bullets){
b.drawBullet();
}
Shameless self-promotion:
Here is a tutorial on creating classes.
Here is a tutorial on using ArrayLists.

How to restart a sketch project in processing?

I am working on a Processing project, but I donĀ“t know how to restart the project once it is over. I have searched and found that the setup() method will make it. But it's not working. Can anyone help me. I would like the sketch to restart by itself once it is finished.
/* OpenProcessing Tweak of *#*http://www.openprocessing.org/sketch/59807*#* */
/* !do not delete the line above, required for linking your tweak if you upload again */
//
// outline: takes an image (image.jpg) and creates a sketch version
//
// procsilas (procsilas#hotmail.com / http://procsilas.net)
//
String iName="image.jpeg";
void setup() {
llegeixImatge("./"+iName);
size(img.width, img.height);
}
// parameters
// NO real control, so be careful
int NP=6000; // 1000 for line art, 10000 for complex images, O(N^2) so be patient!!!
int B=1; // try 2 or 3
float THR=28; // range 5-50
float MD=6; // range 0-10
int NMP=6; // range 1-15
float[][] punts;
color[] cpunts;
int [] usat;
int [] NmP=new int[NMP];
float [] NdmP=new float[NMP];
int inici=0;
PImage img;
void llegeixImatge(String s) {
img = loadImage(s);
img.loadPixels();
}
float fVar(int x, int y) {
// neighborhood 2B+1x2B+1 pixels
float m=0;
for (int k1=-B; k1<=B; k1++) {
for (int k2=-B; k2<=B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
m+=brightness(c);
}
}
m/=float((2*B+1)*(2*B+1));
float v=0;
for (int k1=-B; k1<B; k1++) {
for (int k2=-B; k2<B; k2++) {
color c=img.pixels[(y+k1)*img.width+(x+k2)];
v+=(brightness(c)-m)*(brightness(c)-m);
}
}
v=sqrt(v)/(float) (2*B+1);
return v;
}
void creaPunts() {
punts = new float[NP][2];
cpunts = new color[NP];
usat = new int[NP];
int nint1=0;
int nint2=0;
for (int i=0; i<NP;) {
int x=B+int(random(width-2*B));
int y=B+int(random(height-2*B));
//println(i+" = "+x+", "+y+": "+THR+", "+MD);
// points need to be at least MD far from each other
int flag=0;
if (MD>0.0) {
for (int j=0; flag==0 && j<i; j++) {
if (dist(x, y, punts[j][0], punts[j][1])<MD) {
flag=1;
}
}
}
if (flag==0) {
nint1=0;
float f=fVar(x, y);
// use only "valid" points
if (f>=THR) {
nint2=0;
punts[i][0]=x;
punts[i][1]=y;
cpunts[i]=img.pixels[y*img.width+x];
usat[i]=0;
i++;
}
else {
nint2++;
if (nint2>=10) {
THR/=(1+1.0/float(NP-i));
MD/=(1+1.0/float(NP-i));
nint2=0;
}
}
}
else {
nint1++;
if (nint1>=10) {
MD/=2.0;
THR*=1.618;
nint1=0;
}
}
}
}
int NessimMesProper(int i) {
if (NMP<=1) {
int mP=-1;
float dmP=dist(0, 0, width, height);
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
if (jmP<dmP) {
dmP=jmP;
mP=j;
}
}
}
return mP;
}
else {
for (int j=0; j<NMP; j++) {
NmP[j]=-1;
NdmP[j]=dist(0, 0, width, height);
}
for (int j=0; j<NP; j++) {
if (usat[j]==0) {
float jmP=dist(punts[i][0], punts[i][1], punts[j][0], punts[j][1]);
int k=NMP;
while(k>0 && NdmP[k-1]>jmP) {
k--;
}
if (k<NMP) {
for (int l=0; l<(NMP-k)-1; l++) {
NmP[(NMP-1)-l]=NmP[(NMP-1)-(l+1)];
NdmP[(NMP-1)-l]=NdmP[(NMP-1)-(l+1)];
}
NmP[k]=j;
NdmP[k]=jmP;
}
}
}
return NmP[NMP-1];
}
}
int fase=0;
void draw() {
if (fase==0) {
creaPunts();
background(#FFFFFF);
fase=1;
}
else {
if (inici!=-1) {
stroke(#000000);
usat[inici]=1;
int seguent=NessimMesProper(inici);
if (seguent!=-1) {
line(punts[inici][0], punts[inici][1], punts[seguent][0], punts[seguent][1]);
}
inici=seguent;
}
else {
//save("outline_"+iName);
}
}
}
You should not call setup() yourself.
Step 1: Encapsulate the state of your program in a set of variables.
Step 2: Use those variables to draw your sketch.
Step 3: Modify those variables to change what's being drawn.
Step 4: Simply reset those variables to their initial values when you want to reset the sketch.
Here's an example program that stores its state (the positions the user has clicked) in an ArrayList. It uses that ArrayList to draw the sketch, and new points are added whenever the user clicks. When the user types a key, the sketch is reset by clearing out the ArrayList:
ArrayList<PVector> points = new ArrayList<PVector>();
void setup(){
size(500, 500);
}
void draw(){
background(0);
for(PVector p : points){
ellipse(p.x, p.y, 20, 20);
}
}
void mousePressed(){
points.add(new PVector(mouseX, mouseY));
}
void keyPressed(){
points.clear();
}

Mixing active and static modes in Processing

Making a space invaders knock off game. My code will not compile as I get the error message "It looks like you're mixing 'active' and 'static' modes", but I can not see where I am mixing them. Can someone please take a look at my code?
final int SCREENX=400;
final int SCREENY=400;
final int GAP=10;
final int ALIEN_ALIVE=0;
final int ALIEN_DEAD=6;
final int FORWARD=0;
final int BACKWARD=1;
final int MARGIN=30;
Alien theAliens[];
Bullet bullets[];
Player thePlayer;
void setup() {
PImage normalImg, explodeImg;
size(SCREENX, SCREENY);
normalImg =loadImage("invader.GIF");
explodeImg =loadImage("exploding.GIF");
theAliens = new Alien[10];
bullets = new Bullet[20];
init_aliens(theAliens, normalImg, explodeImg);
thePlayer = new Player(SCREENY- 50);
}
void init_aliens(Alien baddies[], PImage okImg, PImage
exImg) {
for (int i=0; i<baddies.length; i++) {
// This is buggy, what is the problem?
baddies[i] = new Alien(i*(okImg.width+GAP), 0, okImg,
exImg);
}
}
void init_bullets() {
for (int i = 0; i < bullets.size(); i++) {
Bullet b = (Bullet) bullets.get(i);
b.move();
b.draw();
}
}
void shoot() {
if (mousePressed)
Player.shoot();
}
void draw() {
background(0);
thePlayer.draw();
thePlayer.move(mouseX);
draw_bullets(myBullets);
for (int i=0; i<theAliens.length; i++) {
theAliens[i].move();
theAliens[i].draw();
if (random(0, 500)<1)
theAliens[i].die();
}
}
////// Player Class //////
Player() { ///** When I get the error, this line is highlighted**///
this.x = width/2;
this.y = height-50;
this.timeLastShot = 0;
this.coolDown = 200;
colour playColour= color(50);
void draw() {
fill(playerColour);
rect(this.x, this.y, 30, 30);
}
void move(int x) {
if (x>SCREENX-50)
xpos= SCREENX-50;
else xpos=x;
}
void shoot() {
if (millis() - timeLastShot > coolDown) {
Bullet bullet = new Bullet(this.x+12.5, this.y, -5);
bullets.add(bullet);
timeLastShot = millis();
}
}
}
Your Player class is badly written. It should be:
class Player {
Player () {
//constructor
}
void functionOfSorts () {
} // Never forget to enclose functions with curly brackets!
}
...As opposed to what you wrote:
Player() {
//yadayada
}

Resources