Advertisement
dragnoz

Defold - Basic left right movement

Feb 19th, 2017
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. --prehash the inputs
  2. local input_left = hash("left")
  3. local input_right = hash("right")
  4. local input_jump = hash("jump")
  5. local direction = 0
  6.  
  7.  
  8. function init(self)
  9. msg.post(".", "acquire_input_focus")
  10.  
  11. -- maximum speed the instance can be moved
  12. self.max_speed = 100
  13.  
  14. -- velocity of the instance, initially zero
  15. self.velocity = vmath.vector3()
  16.  
  17.  
  18. end
  19.  
  20.  
  21.  
  22. --------- handles animation --------
  23. function animation_direction(self,direction)
  24. if direction == 1 or direction == 2 then
  25. msg.post("#sprite","play_animation", {id = hash("walk")})
  26. end
  27.  
  28. if direction == 1 then
  29. sprite.set_hflip("#sprite", true) --turn to face direction true is oposite from original sprite directio
  30. else if direction == 2 then
  31. sprite.set_hflip("#sprite", false) --false resets to original direction
  32. end end
  33. end
  34.  
  35. ---------- handles input ----------
  36.  
  37. function on_input(self, action_id, action)
  38.  
  39. if action_id == input_left and action.pressed then
  40. direction = 1
  41. animation_direction(self, direction) --- run animation function
  42. self.velocity = vmath.vector3(action.value * -self.max_speed, 0, 0)
  43.  
  44. else if action_id == input_right and action.pressed then
  45. direction = 2
  46. animation_direction(self, direction) --- run animation function
  47. self.velocity = vmath.vector3(action.value * self.max_speed, 0, 0)
  48.  
  49. else if action_id == input_jump then
  50. direction = 3
  51. print("jump")
  52.  
  53. else if action.released then
  54. msg.post("#sprite","play_animation", {id = hash("idle")})
  55. self.velocity = vmath.vector3(action.value * 0, 0, 0)
  56. end
  57.  
  58. end
  59. end
  60. end
  61. end
  62.  
  63.  
  64. function update(self, dt)
  65. -- move the instance
  66. go.set_position(go.get_position() + dt * self.velocity)
  67. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement