def updateMoveButton(self): if self.moveButton1: moveDir = Vector(self.moveButton1.targetPos) - Vector( self.moveButton1.pos) moveDist = moveDir.length() moveVel = self.vMoveVel * self.fFrameTime if moveVel > moveDist: self.moveButton1.pos = self.moveButton1.targetPos self.moveButton1 = None else: moveDir = moveDir.normalize() moveDir *= moveVel self.moveButton1.pos = (self.moveButton1.pos[0] + moveDir[0], self.moveButton1.pos[1] + moveDir[1]) if self.moveButton2: moveDir = Vector(self.moveButton2.targetPos) - Vector( self.moveButton2.pos) moveDist = moveDir.length() moveVel = self.vMoveVel * self.fFrameTime if moveVel > moveDist: self.moveButton2.pos = self.moveButton2.targetPos self.moveButton2 = None else: moveDir = moveDir.normalize() moveDir *= moveVel self.moveButton2.pos = (self.moveButton2.pos[0] + moveDir[0], self.moveButton2.pos[1] + moveDir[1])
def transform_with_touch(self, touch): # just do a simple one finger drag changed = False if len(self._touches) == self.translation_touches: # _last_touch_pos has last pos in correct parent space, # just like incoming touch dx = (touch.x - self._last_touch_pos[touch][0]) \ * self.do_translation_x dy = (touch.y - self._last_touch_pos[touch][1]) \ * self.do_translation_y dx = dx / self.translation_touches dy = dy / self.translation_touches self.apply_transform(Matrix().translate(dx, dy, 0)) changed = True if len(self._touches) == 1: return changed # we have more than one touch... list of last known pos points = [ Vector(self._last_touch_pos[t]) for t in self._touches if t is not touch ] # add current touch last points.append(Vector(touch.pos)) # we only want to transform if the touch is part of the two touches # farthest apart! So first we find anchor, the point to transform # around as another touch farthest away from current touch's pos anchor = max(points[:-1], key=lambda p: p.distance(touch.pos)) # now we find the touch farthest away from anchor, if its not the # same as touch. Touch is not one of the two touches used to transform farthest = max(points, key=anchor.distance) if farthest is not points[-1]: return changed # ok, so we have touch, and anchor, so we can actually compute the # transformation old_line = Vector(*touch.ppos) - anchor new_line = Vector(*touch.pos) - anchor if not old_line.length(): # div by zero return changed angle = radians(new_line.angle(old_line)) * self.do_rotation if angle: changed = True self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor) if self.do_scale: scale = new_line.length() / old_line.length() new_scale = scale * self.scale if new_scale < self.scale_min: scale = self.scale_min / self.scale elif new_scale > self.scale_max: scale = self.scale_max / self.scale self.apply_transform(Matrix().scale(scale, scale, scale), anchor=anchor) changed = True return changed
def on_touch_move(self, touch): if touch.grab_current is not self.transform: return touch_point_in_parent = self.transform.to_parent(*touch.pos) if len(self.touches) == 1 and self.do_translation: ptx, pty = self.transform.pos px0, py0 = self.transform.to_parent(touch.px, touch.py) px1, py1 = touch_point_in_parent pdx, pdy = px1 - px0, py1 - py0 self.transform.pos = ptx + pdx, pty + pdy else: touch_point = Vector(touch_point_in_parent) points = [self.prev_pos[t] for t in self.touches] pivot = max(points, key=touch_point.distance) farthest = max(points, key=pivot.distance) if points.index(farthest) == self.touches.index(touch): old_line = Vector(self.transform.to_parent(*touch.ppos)) - pivot new_line = Vector(touch_point_in_parent) - pivot vx, vy = self.transform.viewport_pos local_pivot = self.transform.to_local(*pivot) self.transform.viewport_pos = vx-local_pivot[0], vy-local_pivot[1] if self.do_rotation: self.transform.do_rotate(radians(new_line.angle(old_line))) if self.do_scale: ratio = new_line.length() / old_line.length() self.transform.do_scale(ratio, ratio) self.transform.viewport_pos = vx, vy self.prev_pos[touch] = Vector(touch_point_in_parent)
def transform_with_touch(self, touch): # just do a simple one finger drag changed = False if len(self._touches) == self.translation_touches: # _last_touch_pos has last pos in correct parent space, # just like incoming touch dx = (touch.x - self._last_touch_pos[touch][0]) \ * self.do_translation_x dy = (touch.y - self._last_touch_pos[touch][1]) \ * self.do_translation_y dx = dx / self.translation_touches dy = dy / self.translation_touches self.apply_transform(Matrix().translate(dx, dy, 0)) changed = True if len(self._touches) == 1: return changed # we have more than one touch... list of last known pos points = [Vector(self._last_touch_pos[t]) for t in self._touches if t is not touch] # add current touch last points.append(Vector(touch.pos)) # we only want to transform if the touch is part of the two touches # farthest apart! So first we find anchor, the point to transform # around as another touch farthest away from current touch's pos anchor = max(points[:-1], key=lambda p: p.distance(touch.pos)) # now we find the touch farthest away from anchor, if its not the # same as touch. Touch is not one of the two touches used to transform farthest = max(points, key=anchor.distance) if farthest is not points[-1]: return changed # ok, so we have touch, and anchor, so we can actually compute the # transformation old_line = Vector(*touch.ppos) - anchor new_line = Vector(*touch.pos) - anchor if not old_line.length(): # div by zero return changed angle = radians(new_line.angle(old_line)) * self.do_rotation if angle: changed = True self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor) if self.do_scale: scale = new_line.length() / old_line.length() new_scale = scale * self.scale if new_scale < self.scale_min: scale = self.scale_min / self.scale elif new_scale > self.scale_max: scale = self.scale_max / self.scale self.apply_transform(Matrix().scale(scale, scale, scale), anchor=anchor) changed = True return changed
def update_last_touch(self, touch): tx, ty = self.last_touches[touch.uid] v = Vector(touch.x - tx, touch.y - ty) v1 = v if 0 < v.length() < self.stroke_error_margin: v = Vector(0, 0) if v.length() > 0: self.stroke_list[touch.uid][-1] = self.round_vector(v.normalize())
def transform_with_touch(self, touch): if self.locked_on_pos: if len(self._touches) == 1: return False changed = False # We have more than one touch... list of last known pos points = [Vector(self._last_touch_pos[t]) for t in self._touches if t is not touch] # Add current touch last points.append(Vector(touch.pos)) # We only want to transform if the touch is part of the two touches # farthest apart! So first we find anchor, the point to transform # around as another touch farthest away from current touch's pos anchor_ = max(points[:-1], key=lambda p: p.distance(touch.pos)) # Now we find the touch farthest away from anchor, if its not the # same as touch. Touch is not one of the two touches used to transform farthest = max(points, key=anchor_.distance) if farthest is not points[-1]: return changed # Ok, so we have touch, and anchor, so we can actually compute the # transformation old_line = Vector(*touch.ppos) - anchor_ new_line = Vector(*touch.pos) - anchor_ if not old_line.length(): # div by zero return changed # pol : we don't want rotation here # angle = radians(new_line.angle(old_line)) * self.do_rotation # self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor) # pol : trick -> change the origin!! anchor = Vector(self.to_parent(*self.last_pos)) if self.do_scale: scale = new_line.length() / old_line.length() new_scale = scale * self.scale if new_scale < self.scale_min: scale = self.scale_min / self.scale elif new_scale > self.scale_max: scale = self.scale_max / self.scale self.apply_transform(Matrix().scale(scale, scale, scale), anchor=anchor) changed = True return changed super(MapViewer, self).transform_with_touch(touch)
def on_touch_down(self, touch): for ball in [self.ball1, self.ball2]: touch_vector = Vec(touch.pos) - Vec(ball.center) touch_vector_mag = touch_vector.length() unit_touch_vector = touch_vector / touch_vector_mag ball.vel = 5.0 * unit_touch_vector print touch_vector
def circleToCircle(a, b): v = Vector(a.pos) - Vector(b.pos) if v.length() < a.r+b.r: return (True, None, v.normalize()) return (False, None, None)
def on_touch_up(self, touch): print("ontouch up") v = Vector(touch.pos) - Vector(touch.opos) if v.length() < dp(20): return # detect direction dx, dy = v if abs(dx) > abs(dy): if dx > 0: self.move("left") else: self.move("right") else: if dy > 0: self.move("up") else: self.move("down") # if game won or lost if self.get_game_status() != None: self.end() self.ended = True if (self.has_empty() or self.can_combine()) and self.moved and not self.ended: Clock.schedule_once(self.spawn_number, .20) return True
def update_widget_graphics(self, *l): if not self.activated: return if self.widget is None: self.grect.size = 0, 0 return gr = self.grect widget = self.widget # determine rotation a = Vector(1, 0) if widget is self.win: b = Vector(widget.to_window(0, 0)) c = Vector(widget.to_window(1, 0)) else: b = Vector(widget.to_window(*widget.to_parent(0, 0))) c = Vector(widget.to_window(*widget.to_parent(1, 0))) - b angle = -a.angle(c) # determine scale scale = c.length() # apply transform gr.size = widget.size if widget is self.win: self.gtranslate.xy = Vector(widget.to_window(0, 0)) else: self.gtranslate.xy = Vector(widget.to_window(*widget.pos)) self.grotate.angle = angle # fix warning about scale property deprecation self.gscale.xyz = (scale, ) * 3
def update_widget_graphics(self, *l): if not self.activated: return if self.widget is None: self.grect.size = 0, 0 return gr = self.grect widget = self.widget # determine rotation a = Vector(1, 0) if widget is self.win: b = Vector(widget.to_window(0, 0)) c = Vector(widget.to_window(1, 0)) else: b = Vector(widget.to_window(*widget.to_parent(0, 0))) c = Vector(widget.to_window(*widget.to_parent(1, 0))) - b angle = -a.angle(c) # determine scale scale = c.length() # apply transform gr.size = widget.size if widget is self.win: self.gtranslate.xy = Vector(widget.to_window(0, 0)) else: self.gtranslate.xy = Vector(widget.to_window(*widget.pos)) self.grotate.angle = angle # fix warning about scale property deprecation self.gscale.xyz = (scale,) * 3
class Ball(Widget): r = 30 / 2 r2 = r**2 trail_pts = [] g_trail = "trail" def setup(self): self.pos = (cx, cy+cy/2) self.velocity = Vector(0,5) def move(self, dt): self.canvas.remove_group(self.g_trail) with self.canvas: Color(1, 1, 1, 0.5, mode='rgba', group=self.g_trail) Line(points=sum(self.trail_pts, []), group=self.g_trail) to_center = (Vector(cx, cy) - Vector(self.pos)) l = self.velocity.length() cen_d = to_center.length() self.velocity = self.velocity * 0.99 + to_center.normalize() * sqrt(cen_d) * 0.04 if l > 25: self.velocity = self.velocity.normalize() * 20 self.pos = Vector(self.pos) + self.velocity * dt * 30 if len(self.trail_pts) == 0: self.trail_pts = [self.pos] else: self.trail_pts.insert(0, self.pos) while len(self.trail_pts) > 30: self.trail_pts.pop()
def circleToCircle(a, b): v = Vector(a.pos) - Vector(b.pos) if v.length() < a.r + b.r: return (True, None, v.normalize()) return (False, None, None)
class Ball(Widget): r = 30 / 2 r2 = r**2 trail_pts = [] g_trail = "trail" def setup(self): self.pos = (cx, cy + cy / 2) self.velocity = Vector(0, 5) def move(self, dt): self.canvas.remove_group(self.g_trail) with self.canvas: Color(1, 1, 1, 0.5, mode='rgba', group=self.g_trail) Line(points=sum(self.trail_pts, []), group=self.g_trail) to_center = (Vector(cx, cy) - Vector(self.pos)) l = self.velocity.length() cen_d = to_center.length() self.velocity = self.velocity * 0.99 + to_center.normalize() * sqrt( cen_d) * 0.04 if l > 25: self.velocity = self.velocity.normalize() * 20 self.pos = Vector(self.pos) + self.velocity * dt * 30 if len(self.trail_pts) == 0: self.trail_pts = [self.pos] else: self.trail_pts.insert(0, self.pos) while len(self.trail_pts) > 30: self.trail_pts.pop()
def on_touch_up(self, touch): if not self.collide_point(*touch.pos): return vec=Vector(touch.pos)-Vector(touch.opos) if vec.length()>10: if abs(vec.x)>abs(vec.y): if vec.x>0: self.fadeMenu()
def _get_acceleration(self, world_object): """Returns object's acceleration change :param world_object: object which acceleration will be changed :type world_object: parabox.base_object.BaseObject :return: acceleration change :rtype: Vector """ acceleration_vector = Vector( self.x - world_object.x, self.y - world_object.y) if self.affect_radius < acceleration_vector.length(): acceleration_vector *= 0 else: acceleration_vector *= ( (1 - acceleration_vector.length() / self.affect_radius) * self.gravity) return acceleration_vector
def move(self): velocity = Vector(*self.acceleration) + self.velocity # avoid going through walls ;) abs_velocity = velocity.length() if abs_velocity > self.max_velocity: velocity *= self.max_velocity / abs_velocity self.velocity = velocity self.pos = velocity + self.pos
def on_touch_up(self, touch): v = Vector(touch.pos) - Vector(touch.opos) if v.length() < dp(20): return # detect direction dx, dy = v if abs(dx) > abs(dy): self.move_leftright(dx > 0) else: self.move_topdown(dy > 0)
def validate(self, touches, strokes): v_orig = Vector(0, 0) for i in self.initial_touches: v_orig = self.initial_touches[i] - v_orig if v_orig.length() > 100: return False v_sum = Vector(0, 0) for t in touches: v_old = self.initial_touches[t.uid] v_new = Vector(t.x, t.y) v_norm = (v_new - v_old).normalize() if v_norm.length() == 0: return False v_sum = v_norm - v_sum return v_sum.length() < 1
def on_touch_up(self, touch): v = Vector(touch.pos) - Vector(touch.opos) if v.length() < 20: return if abs(v.x) > abs(v.y): v.y = 0 else: v.x = 0 self.move(*v.normalize())
def on_touch_up(self, touch): v = Vector(touch.pos) - Vector(touch.opos) if v.length() < 20: return if abs(v.x) > abs(v.y): v.y = 0 else: v.x = 0 if not self.game_over: self.move(*v.normalize())
def transform_with_touch(self, touch): # just do a simple one finger drag if len(self._touches) == 1: # _last_touch_pos has last pos in correct parent space, # just like incoming touch dx = (touch.x - self._last_touch_pos[touch][0]) \ * self.do_translation_x dy = (touch.y - self._last_touch_pos[touch][1]) \ * self.do_translation_y self.apply_transform(Matrix().translate(dx, dy, 0)) return # we have more than one touch... points = [Vector(self._last_touch_pos[t]) for t in self._touches] # we only want to transform if the touch is part of the two touches # furthest apart! So first we find anchor, the point to transform # around as the touch farthest away from touch anchor = max(points, key=lambda p: p.distance(touch.pos)) # now we find the touch farthest away from anchor, if its not the # same as touch. Touch is not one of the two touches used to transform farthest = max(points, key=anchor.distance) if points.index(farthest) != self._touches.index(touch): return # ok, so we have touch, and anchor, so we can actually compute the # transformation old_line = Vector(*touch.ppos) - anchor new_line = Vector(*touch.pos) - anchor angle = radians(new_line.angle(old_line)) * self.do_rotation self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor) if self.do_scale: scale = new_line.length() / old_line.length() new_scale = scale * self.scale if new_scale < self.scale_min or new_scale > self.scale_max: scale = 1.0 self.apply_transform(Matrix().scale(scale, scale, scale), anchor=anchor)
def on_touch_up(self, touch): v = Vector(touch.pos) - Vector(touch.opos) if v.length() < dp(20): return # detect direction dx, dy = v if abs(dx) > abs(dy): self.move_leftright(dx > 0) else: self.move_topdown(dy > 0) return True
def collide_widget(self, widget_to_test_against): collide_vector = Vector((self.rect_bg.pos[0] + self.rect_bg.size[0]/2), (self.rect_bg.pos[1] + self.rect_bg.size[1]/2) ) - \ Vector((widget_to_test_against.rect_bg.pos[0] + widget_to_test_against.rect_bg.size[0]/2), (widget_to_test_against.rect_bg.pos[1] + widget_to_test_against.rect_bg.size[1]/2)) collide_vector_length = collide_vector.length() #assume approximately sqare or spherical widgets...this won't look right for oblong widgets collision_length = (self.rect_bg.size[0]/2) + (widget_to_test_against.rect_bg.size[0]/2) if collide_vector_length < collision_length: print('asteroid.size: {}'.format(self.rect_bg.size)) print('ship.size: {}'.format(widget_to_test_against.rect_bg.size)) print('collide_vector_length: {}'.format(collide_vector_length)) print('collision_length: {}'.format(collision_length)) return True
def on_touch_up(self, touch): v = Vector(touch.pos) - Vector(touch.opos) if v.length() < 20: return # 比较绝对值 if abs(v.x) > abs(v.y): v.y = 0 else: v.x = 0 # 移动 self.move(*v.normalize())
def updateMoveButton(self): if self.moveButton1: moveDir = Vector(self.moveButton1.targetPos) - Vector(self.moveButton1.pos) moveDist = moveDir.length() moveVel = self.vMoveVel * self.fFrameTime if moveVel > moveDist: self.moveButton1.pos = self.moveButton1.targetPos self.moveButton1 = None else: moveDir = moveDir.normalize() moveDir *= moveVel self.moveButton1.pos = (self.moveButton1.pos[0] + moveDir[0], self.moveButton1.pos[1] + moveDir[1]) if self.moveButton2: moveDir = Vector(self.moveButton2.targetPos) - Vector(self.moveButton2.pos) moveDist = moveDir.length() moveVel = self.vMoveVel * self.fFrameTime if moveVel > moveDist: self.moveButton2.pos = self.moveButton2.targetPos self.moveButton2 = None else: moveDir = moveDir.normalize() moveDir *= moveVel self.moveButton2.pos = (self.moveButton2.pos[0] + moveDir[0], self.moveButton2.pos[1] + moveDir[1])
def move(self, previousPart, magnitude): #moves an individual part #first calculates the previous part's position and vectorizes it previousPos = (previousPart.absolutePos[0],previousPart.absolutePos[1]) destination = Vector(previousPos[0], previousPos[1]) current = (self.absolutePos[0], self.absolutePos[1]) velocity = Vector(destination.x-current[0],destination.y-current[1]) #determines velocity based on destination and current position if destination.distance(current) < self.width: #realigns the part velocity so that parts don't outrun the head #when the head turns magnitude *= velocity.length() / self.width velocity = velocity.normalize() * magnitude self.absolutePos[0] += velocity.x self.absolutePos[1] += velocity.y self.wrapAround()
def highlight_at(self, *largs): '''A function to highlight the current self.widget''' gr = self.grect widget = self.widget # determine rotation a = Vector(1, 0) b = Vector(widget.to_window(*widget.to_parent(0, 0))) c = Vector(widget.to_window(*widget.to_parent(1, 0))) - b angle = -a.angle(c) # determine scale scale = c.length() # apply transform gr.size = widget.size self.gtranslate.xy = Vector(widget.to_window(*widget.pos)) self.grotate.angle = angle self.gscale.scale = scale
def on_touch_move(self, *args): # print("on_touch_down", args) touch = args[0] # print(touch.pos, self.center) # self.stick.center = touch.pos center2touch = Vector(*touch.pos) - Vector(*self.center) # print("center2touch", center2touch) dist = center2touch.length() # print("dist", dist) self.angle = -Vector(1, 0).angle(center2touch) # print("angle", self.angle) pos2center = Vector(*self.center) - Vector(*self.pos) if dist > self.max_dist: dist = self.max_dist center2touch = center2touch.normalize() * self.max_dist self.stick.center = center2touch + pos2center self.magnitude = dist / self.max_dist
def move(self, previousPart, magnitude): #moves an individual part #first calculates the previous part's position and vectorizes it previousPos = (previousPart.absolutePos[0], previousPart.absolutePos[1]) destination = Vector(previousPos[0], previousPos[1]) current = (self.absolutePos[0], self.absolutePos[1]) velocity = Vector(destination.x - current[0], destination.y - current[1]) #determines velocity based on destination and current position if destination.distance(current) < self.width: #realigns the part velocity so that parts don't outrun the head #when the head turns magnitude *= velocity.length() / self.width velocity = velocity.normalize() * magnitude self.absolutePos[0] += velocity.x self.absolutePos[1] += velocity.y self.wrapAround()
def update(self, dt): for ball in [self.ball1, self.ball2]: if ball.collide_widget(self.wall_left): ball.vel[0] = abs(ball.vel[0]) elif ball.collide_widget(self.wall_right): ball.vel[0] = -abs(ball.vel[0]) if ball.collide_widget(self.wall_top): ball.vel[1] = -abs(ball.vel[1]) elif ball.collide_widget(self.wall_down): ball.vel[1] = abs(ball.vel[1]) if self.ball1.collide_widget(self.ball2): col_vector = Vec(self.ball1.pos) - Vec(self.ball2.pos) col_vector_mag = col_vector.length() self.ball1.vel = 5.0 / col_vector_mag * col_vector self.ball2.vel = -5.0 / col_vector_mag * col_vector self.ball1.pos = Vec(self.ball1.vel) + Vec(self.ball1.pos) self.ball2.pos = Vec(self.ball2.vel) + Vec(self.ball2.pos)
def update(self,dt): for ball in [self.ball1,self.ball2]: if ball.collide_widget(self.wall_left): ball.vel[0] *= -1 elif ball.collide_widget(self.wall_right): ball.vel[0] *= -1 if ball.collide_widget(self.wall_top): ball.vel[1] *= -1 elif ball.collide_widget(self.wall_down): ball.vel[1] *= -1 if self.ball1.collide_widget(self.ball2): col_vector = Vec(self.ball1.pos) - Vec(self.ball2.pos) col_vector_mag=col_vector.length() self.ball1.vel = 5.0/col_vector_mag*col_vector self.ball2.vel = -5.0/col_vector_mag*col_vector self.ball1.pos = Vec(self.ball1.vel) + Vec(self.ball1.pos) self.ball2.pos = Vec(self.ball2.vel) + Vec(self.ball2.pos)
def validate(self, touches, strokes): v_sum = Vector(0, 0) sum_dot_base = 0 for t in touches: v_old = Vector(self.initial_touches[t.uid][0], self.initial_touches[t.uid][1]) v_new = Vector(t.x, t.y) v_norm = (v_new - v_old).normalize() if v_norm.length() == 0: return False v_base = (v_old - self.center).normalize() print(v_old, v_new, v_norm, v_base, v_base.dot(v_norm)) sum_dot_base += v_base.dot(v_norm) v_sum += v_norm return abs(sum_dot_base) >= 1.85 and v_sum.length() < 1
def on_touch_up(self, touch): # Debug section self.touch_console_pos = self.con.get_console_pos((touch.x, touch.y)) self.touch_info['pos'] = touch.pos self.touch_info['time_start'] = touch.time_start self.touch_info['time_update'] = touch.time_update self.touch_info['time_end'] = touch.time_end self.touch_info['triple_tap_time'] = touch.triple_tap_time self.touch_info['double_tap_time'] = touch.double_tap_time # Start of move code vec = Vector(touch.pos) - Vector(touch.opos) # If travel distance is short then it's probably a tap or click. if vec.length() < 50: return dx, dy = vec.normalize() self.player.move(round(dx), round(dy)) self.update()
def on_touch_move(self, touch): if "vjtouch" not in touch.ud: return vec = Vector(touch.pos) - Vector(self.center) vlen = vec.length() if vlen > self.radius: vec = vec.normalize() * self.radius stripsize = 0.2 try: if vlen < self.radius * stripsize or \ self.radius * (1.0 + stripsize) > vlen > self.radius: vibrator.vibrate(0.005) except NotImplementedError: pass self.touch = Vector(self.center) + vec self.vec = vec / self.radius
def on_touch_up(self, touch): if self.vProg.collide_point(*touch.pos) and hasattr(self,"vprev") and touch is self.vtouch: self.video.seek(self.vProg.value) self.thumb.opacity=0 if self.video.state!="stop": self.video.state=self.vprev self.video.bind(position=self.posListen) return vec=Vector(touch.pos)-Vector(touch.opos) if vec.length()<10: return if abs(vec.x)<abs(vec.y): about=About() about.open() return if abs(vec.x)>abs(vec.y): if vec.x<0: self.openFileChooser() if vec.x>0: self.openPlayerList() super(KVideoplayer,self).on_touch_up(touch)
def update_widget_graphics(self, *l): if not self.activated: return if self.widget is None: self.grect.size = 0, 0 return gr = self.grect widget = self.widget # determine rotation a = Vector(1, 0) b = Vector(widget.to_window(*widget.to_parent(0, 0))) c = Vector(widget.to_window(*widget.to_parent(1, 0))) - b angle = -a.angle(c) # determine scale scale = c.length() # apply transform gr.size = widget.size self.gtranslate.xy = Vector(widget.to_window(*widget.pos)) self.grotate.angle = angle self.gscale.scale = scale
def _update_velocity(self): """Change velocity because of acceleration""" self.velocity = Vector(*self.velocity) + Vector(*self.acceleration) velocity_vector = Vector(self.velocity) if velocity_vector.length() > self.speed_limit: self.velocity = velocity_vector * self.speed_limit / velocity_vector.length()
class Game(Widget): rotational_speed = kp.NumericProperty(PLAYER_ROTATIONAL_SPEED * Window.width) side = kp.StringProperty("") last_side = kp.StringProperty("") vel = kp.ObjectProperty(Vector(0, 0)) acc = kp.ObjectProperty(Vector(0, 0)) origin = kp.ObjectProperty( Vector(BALL_ORIGIN_X * Window.width, BALL_ORIGIN_Y * Window.height)) start_launch = kp.BooleanProperty(False) finish_launch = kp.BooleanProperty(False) def new(self): self.vel = Vector(0, 0) def update(self, dt): # print(dt) # update player: self.player_left.angle += self.player_left.rotational_speed * dt self.player_right.angle += self.player_right.rotational_speed * dt self.player_left.angle = max(self.player_left.angle, PLAYER_MIN_ANGLE) self.player_right.angle = min(self.player_right.angle, -PLAYER_MIN_ANGLE) self.player_left.angle = min(self.player_left.angle, PLAYER_MAX_ANGLE) self.player_right.angle = max(self.player_right.angle, -PLAYER_MAX_ANGLE) # update ball: if self.ball.y > BALL_ORIGIN_Y * Window.height and not self.finish_launch: print("ultrapassou", self.vel.y) speed = self.vel.length() self.acc = Vector(self.origin - Vector(self.ball.pos)).normalize( ) * BALL_ACC * speed * dt if not self.finish_launch and self.vel.y < 0: print("stop rotate") self.finish_launch = True self.acc = Vector(0, 0) self.vel += self.acc self.ball.pos = Vector(self.ball.pos) + self.vel * dt print("ball", self.ball.pos, self.vel) # collisions: if self.ball.x <= 0: self.ball.x = 0 self.vel.x *= -1 if self.ball.right >= Window.width: self.ball.right = Window.width self.vel.x *= -1 if self.ball.top >= Window.height: self.ball.top = Window.height self.vel.y *= -1 def on_touch_down(self, touch): print(touch) if self.ball.collide_point(*touch.pos) and not self.start_launch: self.vel.y = BALL_SPEED_INIT * Window.height self.start_launch = True if touch.x <= Window.width / 2: print("left") self.side = "left" self.last_side = "left" self.player_left.rotational_speed = self.rotational_speed self.player_left.touching = True else: print("right") self.side = "right" self.last_side = "right" self.player_right.rotational_speed = -self.rotational_speed self.player_right.touching = True def on_touch_up(self, touch): if touch.x <= Window.width / 2: print("left") self.player_left.rotational_speed = -self.rotational_speed self.player_left.touching = False else: print("right") self.player_right.rotational_speed = self.rotational_speed self.player_right.touching = False self.side = "" self.last_side = "" def on_touch_move(self, touch): self.side = "left" if touch.x <= Window.width / 2 else "right" if self.side != self.last_side: print("release") if self.side == "right": self.player_left.rotational_speed = -self.rotational_speed self.player_left.touching = False elif self.side == "left": self.player_right.rotational_speed = self.rotational_speed self.player_right.touching = False self.last_side = self.side
def update(self, dt): # collisions: # stick collide with the balls: if self.stick.collide_widget( self.white_ball) and self.shoot_power != 0: print("collide with white ball") dx = cos(self.stick.angle * pi / 180 + pi / 2) * self.shoot_power dy = sin(self.stick.angle * pi / 180 + pi / 2) * self.shoot_power self.white_ball.dx = dx self.white_ball.dy = dy try: self.anim.cancel(self.stick) except: pass # collisions with borders: for ball in self.balls: if ball.top > self.table.top: ball.top = self.table.top ball.dy *= -1 if ball.y < self.table.y: ball.y = self.table.y ball.dy *= -1 if ball.right > self.table.right: ball.right = self.table.right ball.dx *= -1 if ball.x < self.table.x: ball.x = self.table.x ball.dx *= -1 # collision ball1-ball2: for ball1, ball2 in [(self.balls[0], self.balls[1]), (self.balls[0], self.balls[2]), (self.balls[1], self.balls[2])]: if ball1.collide_widget(ball2): ball1_pos = Vector(*ball1.pos) print(ball2) ball2_pos = Vector(*ball2.pos) dist_ball1_ball2 = ball1_pos.distance(ball2_pos) offset = max(ball1.width - dist_ball1_ball2, 0) ball1_vel = Vector(ball1.dx, ball1.dy) half_speed = ball1_vel.length() / 2 angle_vel = ball1_vel.angle(Vector(1, 0)) angle_ball1_ball2 = Vector(ball2.x - ball1.x, ball2.y - ball1.y).angle( Vector(1, 0)) angle_desv_perp_collision = angle_ball1_ball2 + (90 - angle_vel) angle_ball1 = angle_desv_perp_collision + angle_ball1_ball2 + 90 ball1_vel = Vector(half_speed, 0).rotate(angle_ball1) ball1.dx = ball1_vel.x ball1.dy = ball1_vel.y angle_ball2 = angle_ball1_ball2 + 90 - angle_desv_perp_collision ball_1 = Vector(half_speed, 0).rotate(angle_ball2) ball2.dx = ball_1.x ball2.dy = ball_1.y vector_offset = Vector(offset, 0).rotate(angle_ball1) ball1.x += vector_offset.x ball1.y += vector_offset.y for ball in self.balls: print("ball", ball, ball.x, ball.y, ball.dx, ball.dy) # Collide with holes: for hole in self.holes: if hole.collide_point(*ball.center): self.remove_widget(ball) # Friction: ball.frictionx = ball.dx * BALL_FRICTION * dt ball.frictiony = ball.dy * BALL_FRICTION * dt # kinematic equations: ball.x += ball.dx * dt ball.y += ball.dy * dt ball.dx -= ball.frictionx ball.dy -= ball.frictiony if abs(ball.dx) < 0.01: ball.dx = 0 if abs(ball.dy) < 0.01: ball.dy = 0
def test_normalize_zerovector(self): vector = Vector(0,0).normalize() self.assertEqual(vector.x, 0) self.assertEqual(vector.y, 0) self.assertEqual(vector.length(), 0)
def test_normalize(self): vector = Vector(88, 33).normalize() self.assertEqual(vector.x, 0.93632917756904444) self.assertEqual(vector.y, 0.3511234415883917) self.assertEqual(vector.length(),1.0)
def test_normalize_zerovector(self): vector = Vector(0, 0).normalize() self.assertEqual(vector.x, 0) self.assertEqual(vector.y, 0) self.assertEqual(vector.length(), 0)
def process(self, touches, strokes): v = Vector(touches[1].x, touches[1].y) - Vector( touches[0].x, touches[0].y) ratio = v.length() / self.initial_distance self.get_app().fire_event("on_gesture_pinch", ratio, self.center)
def transform_with_touch(self, touch): init_pos = self.center init_scale = self.scale init_touch_len = len(self._touches) #super(ZIScatter, self).transform__with__touch(touch) # just do a simple one finger drag if len(self._touches ) == 1 and self.scale > 1.05: #THIS IS NOT IN ORIGINAL SCATTER: # _last_touch_pos has last pos in correct parent space, # just like incoming touch dx = (touch.x - self._last_touch_pos[touch][0]) \ * self.do_translation_x dy = (touch.y - self._last_touch_pos[touch][1]) \ * self.do_translation_y self.apply_transform(Matrix().translate(dx, dy, 0)) #return elif len( self._touches ) == 1 and self.scale < 1.05: #THIS IS NOT IN ORIGINAL SCATTER: return else: #TO AVOID RETURN IN ORIGINAL SCATTER # we have more than one touch... points = [Vector(self._last_touch_pos[t]) for t in self._touches] # we only want to transform if the touch is part of the two touches # furthest apart! So first we find anchor, the point to transform # around as the touch farthest away from touch anchor = max(points, key=lambda p: p.distance(touch.pos)) # now we find the touch farthest away from anchor, if its not the # same as touch. Touch is not one of the two touches used to transform farthest = max(points, key=anchor.distance) if points.index(farthest) != self._touches.index(touch): return # ok, so we have touch, and anchor, so we can actually compute the # transformation old_line = Vector(*touch.ppos) - anchor new_line = Vector(*touch.pos) - anchor angle = radians(new_line.angle(old_line)) * self.do_rotation self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor) if self.do_scale: scale = new_line.length() / old_line.length() new_scale = scale * self.scale if new_scale < self.scale_min or new_scale > self.scale_max: scale = 1.0 self.apply_transform(Matrix().scale(scale, scale, scale), anchor=anchor) #avoid scatter leaving its box limitx, limity = self.is_leaving_its_box() if limitx or limity: #cancel previous apply_transform if init_touch_len == 1: ddx = ddy = 0 if limitx: ddx = -dx if limity: ddy = -dy self.apply_transform(Matrix().translate(ddx, ddy, 0)) else: if self.do_scale: #self.apply_transform(Matrix().scale(scale/init_scale, scale/init_scale, scale/init_scale), # anchor=anchor) # control #limitx, limity = self.is_leaving_its_box() #if limitx or limity: self.fix_after_leaving_its_box()
def test_normalize(self): vector = Vector(88, 33).normalize() self.assertEqual(vector.x, 0.93632917756904444) self.assertEqual(vector.y, 0.3511234415883917) self.assertAlmostEqual(vector.length(), 1.0)
class Game(Widget): bricks = kp.ListProperty([]) n_of_bricks_rows = kp.NumericProperty(N_OF_BRICKS_ROWS) factor = kp.NumericProperty(1) factor_log = kp.NumericProperty(1) paused = kp.BooleanProperty(True) game_over = kp.BooleanProperty(False) level = kp.NumericProperty(1) def __init__(self, **kwargs): super().__init__(**kwargs) def new(self): self.paused = True self.game_over = False for brick in self.bricks.copy(): brick.kill() # Factors: self.factor = DIFICULTY_BY_LEVEL / (self.level + DIFICULTY_BY_LEVEL - 1) self.factor_log = log(self.level, LOG_BASE) + 1 print("factors", self.factor, self.factor_log) # Player: self.player.center_x = self.width / 2 # Ball: self.vel = Vector(BALL_SPEED * self.factor_log, BALL_SPEED * self.factor_log) self.ball.center_x = Window.width / 2 self.ball.y = self.player.top + 1 for row in range(int(N_OF_BRICKS_ROWS * self.factor_log)): for col in range(int(N_OF_BRICKS_COLS * self.factor_log)): new_brick = Brick(row, col, self.factor_log) self.bricks.append(new_brick) self.add_widget(new_brick) def on_touch_down(self, touch): if self.paused: self.paused = False if self.button_restart.collide_point(*touch.pos): print("bricks", len(self.bricks), self.children) self.new() print("bricks", len(self.bricks), self.children) def on_touch_move(self, touch): # print("move", touch) if self.game_over: return self.player.center_x = touch.x def update(self, dt): # print(dt) if self.paused or self.game_over: return adjust_x = self.parent.width * dt adjust_y = self.parent.height * dt # apply movement self.ball.x += self.vel.x * adjust_x self.ball.y += self.vel.y * adjust_y # check borders: if self.ball.right >= self.parent.width or self.ball.x <= 0: self.vel.x *= -1 self.ball.x += self.vel.x * adjust_x if self.ball.top >= self.parent.height: self.vel.y *= -1 self.ball.y += self.vel.y * adjust_y if self.ball.y <= 0: self.game_over = True # collisions: # collision: ball and player if self.ball.collide_widget(self.player): print("collide", self.ball.pos) # check if hit some corner: speed = self.vel.length() ball_center = Vector(self.ball.center) topleft = Vector(self.player.x, self.player.top) # botleft = Vector(self.player.x, self.player.y) topright = Vector(self.player.right, self.player.top) # botright = Vector(self.player.right, self.player.y) hit_topleft = topleft.distance(ball_center) <= self.ball.radius # # hit_botleft = botleft.distance(ball_center) <= self.ball.radius hit_topright = topright.distance( ball_center) <= self.ball.radius # # hit_botright = botright.distance( ball_center) <= self.ball.radius dx = self.ball.center_x - topright.x dy = self.ball.center_y - topright.y alpha = Vector(dx, dy).angle(Vector(1, 0)) if self.player.x < self.ball.center_x < self.player.right: self.vel.y *= -1 elif hit_topright or hit_topleft: print(hit_topleft, hit_topright, speed, alpha) self.vel = Vector(speed, 0).rotate(alpha) print(self.vel) self.ball.y += self.vel.y * adjust_y # collision: ball and bricks for brick in self.bricks: if self.ball.collide_widget(brick): print("destroy", brick) self.vel.y *= -1 self.remove_widget(brick) self.bricks.remove(brick) if len(self.bricks) == 0: self.level += 1 self.new()