actor.py 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 stop_actions(self, action_types: typing.Tuple[typing.Type[cocos.actions.Action], ...]) -> None:
  41. for action in self.actions:
  42. if isinstance(action, action_types):
  43. self.remove_action(action)
  44. def update_cshape(self) -> None:
  45. self.cshape = collision_model.AARectShape(
  46. euclid.Vector2(self.position[0], self.position[1]),
  47. self.width // 2,
  48. self.height // 2,
  49. )
  50. self.need_update_cshape = False
  51. def update_position(self, new_position: euclid.Vector2) -> None:
  52. self.position = new_position
  53. self.cshape.center = new_position # Note: if remove: strange behaviour: drag change actor position with anomaly
  54. def build_animation_images(self) -> None:
  55. """
  56. Fill self.animation_images with self.animation_image_paths
  57. :return: None
  58. """
  59. for animation_name, animation_image_paths in self.animation_image_paths.items():
  60. self.animation_images[animation_name] = []
  61. for animation_image_path in animation_image_paths:
  62. self.animation_images[animation_name].append(pyglet.resource.image(animation_image_path))
  63. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  64. return self.animation_images.get(animation_name)
  65. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  66. return self.current_image
  67. def update_image(self, new_image: pyglet.image.TextureRegion):
  68. self.image = new_image
  69. self.image_anchor = new_image.width // 2, new_image.height // 2