actor.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # coding: utf-8
  2. import typing
  3. import pyglet
  4. import cocos
  5. from cocos import collision_model
  6. from cocos import euclid
  7. from synergine2.simulation import Subject
  8. from synergine2_cocos2d.animation import AnimatedInterface
  9. class Actor(AnimatedInterface, cocos.sprite.Sprite):
  10. animation_image_paths = {} # type: typing.Dict[str, typing.List[str]]
  11. animation_images = {} # type: typing.Dict[str, typing.List[pyglet.image.TextureRegion]]
  12. def __init__(
  13. self,
  14. image: pyglet.image.TextureRegion,
  15. subject: Subject,
  16. position=(0, 0),
  17. rotation=0,
  18. scale=1,
  19. opacity=255,
  20. color=(255, 255, 255),
  21. anchor=None,
  22. **kwargs
  23. ):
  24. super().__init__(
  25. image,
  26. position,
  27. rotation,
  28. scale,
  29. opacity,
  30. color,
  31. anchor,
  32. **kwargs
  33. )
  34. self.subject = subject
  35. self.cshape = None # type: collision_model.AARectShape
  36. self.update_cshape()
  37. self.build_animation_images()
  38. self.current_image = image
  39. self.need_update_cshape = False
  40. def update_cshape(self) -> None:
  41. self.cshape = collision_model.AARectShape(
  42. euclid.Vector2(self.position[0], self.position[1]),
  43. self.width // 2,
  44. self.height // 2,
  45. )
  46. self.need_update_cshape = False
  47. def update_position(self, new_position: euclid.Vector2) -> None:
  48. self.position = new_position
  49. self.cshape.center = new_position # Note: if remove: strange behaviour: drag change actor position with anomaly
  50. def build_animation_images(self) -> None:
  51. """
  52. Fill self.animation_images with self.animation_image_paths
  53. :return: None
  54. """
  55. for animation_name, animation_image_paths in self.animation_image_paths.items():
  56. self.animation_images[animation_name] = []
  57. for animation_image_path in animation_image_paths:
  58. self.animation_images[animation_name].append(pyglet.resource.image(animation_image_path))
  59. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  60. return self.animation_images.get(animation_name)
  61. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  62. return self.current_image
  63. def update_image(self, new_image: pyglet.image.TextureRegion):
  64. self.image = new_image
  65. self.image_anchor = new_image.width // 2, new_image.height // 2