Анимация спрайта - Java

Узнай цену своей работы

Формулировка задачи:

Помогите чем могете?(Хочу реализовать анимированное движение персонажа, т.е при нажатии например клавиши Left происходила покадровая смена картинки, вроде все должно работать , но выдает ошибку...вот код трех классов взаимосвязанных
Листинг программы
  1. package GameState;
  2. import Entity.Heroy;
  3. import Main.Board;
  4. import TileMap.Tile;
  5. import TileMap.TileMap;
  6. import TileMap.TileType;
  7. import Utils.Loader;
  8. import Utils.TextureAtlas;
  9. import java.awt.*;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. /**
  13. * Created by Denis on 08.09.2016.
  14. */
  15. public class Level2 extends GameState {
  16. //Player
  17. private Heroy heroy;
  18. //Map
  19. private TileMap tileMap;
  20.  
  21. public Level2(GameStateManager gsm) {
  22. super(gsm);
  23. //инициализация данных
  24. init();
  25. }
  26. @Override
  27. public void init() {
  28. tileMap = new TileMap();
  29. heroy = new Heroy(tileMap);
  30. //начальные координаты Player
  31. heroy.setX(100);
  32. heroy.setY(123);
  33. }
  34. @Override
  35. public void tick() {
  36. heroy.tick();
  37. }
  38. @Override
  39. public void handleInput() {
  40. }
  41. @Override
  42. public void render(Graphics g) {
  43. tileMap.render(g);
  44. heroy.render(g);
  45. }
  46. }
Класс анимация
Листинг программы
  1. package Sprite;
  2. import java.awt.image.BufferedImage;
  3. /**
  4. * Created by Denis on 20.09.2016.
  5. */
  6. public class Animation {
  7. private BufferedImage [] frame;
  8. private int currentFrame;
  9. private long startTime;
  10. private long delay;
  11. public Animation (){
  12. }
  13. public void setFrame(BufferedImage [] frame){
  14. this.frame = frame;
  15. if(currentFrame >= frame.length) currentFrame = 0;
  16. }
  17. public void setDelay(long delay){
  18. this.delay = delay;
  19. }
  20. public void tick(){
  21. if(delay == -1) return;
  22. long elepsed = (System.nanoTime() - startTime) / 1000000;
  23. if(elepsed > delay){
  24. currentFrame++;
  25. startTime = System.nanoTime();
  26. }
  27. if(currentFrame == frame.length) currentFrame = 0;
  28. }
  29. public BufferedImage getImage(){
  30. return frame[currentFrame];
  31. }
  32. }
и класс самого персонажа
Листинг программы
  1. package Entity;
  2. import Input.KeyInput;
  3. import Main.Board;
  4. import Sprite.Sprite;
  5. import Sprite.SpriteSheet;
  6. import TileMap.TileMap;
  7. import Utils.TextureAtlas;
  8. import Sprite.Animation;
  9. import java.awt.*;
  10. import java.awt.event.KeyEvent;
  11. import java.awt.image.BufferedImage;
  12. /**
  13. * Created by Denis on 09.09.2016.
  14. */
  15. public class Heroy {
  16. private double x;
  17. private double y;
  18. private double dx;
  19. private double dy;
  20. private int width;
  21. private int height;
  22.  
  23. private boolean up;
  24. private boolean down;
  25. private boolean left;
  26. private boolean right;
  27.  
  28. private TileMap tileMap;
  29. private TextureAtlas atlas;
  30. private SpriteSheet sheet;
  31. private Sprite sprite;
  32. //Рисунок движений по сторонам
  33. private SpriteSheet sheetUP;
  34. private SpriteSheet sheetDown;
  35. private SpriteSheet sheetLeft;
  36. private SpriteSheet sheetRight;
  37. private Animation animation;
  38. //ArraySprites move
  39. private BufferedImage [] upMove ;
  40. private BufferedImage [] downMove ;
  41. private BufferedImage [] leftMove ;
  42. private BufferedImage [] rightMove ;
  43. private int curFrame = 0;
  44. public Heroy(TileMap tileMap){
  45. this.atlas = atlas;
  46. this.tileMap = tileMap;
  47. init();
  48. }
  49. public void init(){
  50. atlas = new TextureAtlas("images/playerSprite.png");
  51. sheet = new SpriteSheet(atlas.cut(0, 0, 96 ,128),12,32);
  52. sheetUP = new SpriteSheet(atlas.cut(0, 96, 96 ,32),3,32);
  53. upMove = new BufferedImage[]{
  54. sheetUP.getSprite(0),
  55. sheetUP.getSprite(1),
  56. sheetUP.getSprite(2)};
  57. sheetDown = new SpriteSheet(atlas.cut(0,0,96,32),3,32);
  58. downMove = new BufferedImage[]{
  59. sheetDown.getSprite(0),
  60. sheetDown.getSprite(1),
  61. sheetDown.getSprite(2)};
  62. sheetLeft = new SpriteSheet(atlas.cut(0,32,96,32),3,32);
  63. leftMove = new BufferedImage[]{
  64. sheetLeft.getSprite(0),
  65. sheetLeft.getSprite(1),
  66. sheetLeft.getSprite(2)};
  67. sheetRight = new SpriteSheet(atlas.cut(0,64,96,32),3,32);
  68. rightMove = new BufferedImage[]{
  69. sheetRight.getSprite(0),
  70. sheetRight.getSprite(1),
  71. sheetRight.getSprite(2)};
  72. animation = new Animation();
  73. }
  74. public void tick(){
  75. handleInput();
  76. if(left){
  77. animation.setFrame(leftMove);
  78. animation.setDelay(100);
  79. }
  80. if(right){
  81. animation.setFrame(rightMove);
  82. animation.setDelay(100);
  83. }
  84. if(up){
  85. animation.setFrame(upMove);
  86. animation.setDelay(100);
  87. }
  88. if(down){
  89. animation.setFrame(downMove);
  90. animation.setDelay(100);
  91. }
  92. animation.tick();
  93. }
  94. //Движение сущности
  95. public void handleInput(){
  96. if(KeyInput.keys[KeyEvent.VK_LEFT]) {
  97. left = true;
  98. x-=3;
  99. }else left = false;
  100. if(KeyInput.keys[KeyEvent.VK_RIGHT]) {
  101. right = true;
  102. x+=3;
  103. }else right = false;
  104. if(KeyInput.keys[KeyEvent.VK_UP]) {
  105. up = true;
  106. y-=3;
  107. }else up = false;
  108. if(KeyInput.keys[KeyEvent.VK_DOWN]) {
  109. down = true;
  110. y+=3;
  111. }else down = false;
  112.  
  113. }
  114.  
  115. public void render(Graphics g) {
  116. g.drawImage(animation.getImage(),(int)x,(int)y,null);
  117.  
  118. //sprite.render(g,120,120);
  119. // g.setColor(Color.red);
  120. // g.drawImage(atlas.cut(0,0,32,32),(int)(tx + x - width /2),(int)(ty +y - width/2),width,height,null);
  121. //g.fillRect((int)(tx + x - width /2),(int)(ty + y -width /2),width,height);
  122. }
  123.  
  124. public double getX(){
  125. return x;
  126. }
  127. public double getY(){
  128. return y;
  129. }
  130. public void setX(int x){
  131. this.x = x;
  132. }
  133. public void setY(int y){
  134. this.y = y;
  135. }
  136. }
Если нужно, то вот весь проект на github https://github.com/deniSinyukov2016/MazeGame.git

Решение задачи: «Анимация спрайта»

textual
Листинг программы
  1. currentFrame  = (currentFrame + 1) % frame.length;

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 3.8 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут