actor.py 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. properties: dict=None,
  23. **kwargs
  24. ):
  25. super().__init__(
  26. image,
  27. position,
  28. rotation,
  29. scale,
  30. opacity,
  31. color,
  32. anchor,
  33. **kwargs
  34. )
  35. self.subject = subject
  36. self.cshape = None # type: collision_model.AARectShape
  37. self.update_cshape()
  38. self.build_animation_images()
  39. self.current_image = image
  40. self.need_update_cshape = False
  41. self.properties = properties or {}
  42. def stop_actions(self, action_types: typing.Tuple[typing.Type[cocos.actions.Action], ...]) -> None:
  43. for action in self.actions:
  44. if isinstance(action, action_types):
  45. self.remove_action(action)
  46. def update_cshape(self) -> None:
  47. self.cshape = collision_model.AARectShape(
  48. euclid.Vector2(self.position[0], self.position[1]),
  49. self.width // 2,
  50. self.height // 2,
  51. )
  52. self.need_update_cshape = False
  53. def update_position(self, new_position: euclid.Vector2) -> None:
  54. self.position = new_position
  55. self.cshape.center = new_position # Note: if remove: strange behaviour: drag change actor position with anomaly
  56. def build_animation_images(self) -> None:
  57. """
  58. Fill self.animation_images with self.animation_image_paths
  59. :return: None
  60. """
  61. for animation_name, animation_image_paths in self.animation_image_paths.items():
  62. self.animation_images[animation_name] = []
  63. for animation_image_path in animation_image_paths:
  64. self.animation_images[animation_name].append(pyglet.resource.image(animation_image_path))
  65. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  66. return self.animation_images.get(animation_name)
  67. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  68. return self.current_image
  69. def update_image(self, new_image: pyglet.image.TextureRegion):
  70. self.image = new_image
  71. self.image_anchor = new_image.width // 2, new_image.height // 2