本文整理汇总了Python中vector.Vector.normalize方法的典型用法代码示例。如果您正苦于以下问题:Python Vector.normalize方法的具体用法?Python Vector.normalize怎么用?Python Vector.normalize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类vector.Vector
的用法示例。
在下文中一共展示了Vector.normalize方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_normalize
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def test_normalize(self):
v1 = Vector([6, 6, 3])
v2 = Vector([1.0, 1.0, 0.5])
self.compareVector(v1.normalize().vec, v2.vec)
v1 = Vector([0, 0, 0])
v2 = Vector([0, 0, 0])
self.compareVector(v1.normalize().vec, v2.vec)
v1 = Vector([0.5, 0, 0])
v2 = Vector([1.0, 0, 0])
self.compareVector(v1.normalize().vec, v2.vec)
示例2: _evade
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def _evade(self, person, others):
target = Vector(0, 0)
for other in others:
if other is person:
continue
distance = person.pos - other.pos
if distance.length2 > FAN_EVADE_DISTANCE ** 2:
distance = Vector(0, 0)
else:
distance.normalize()
target += distance
target.normalize()
return target
示例3: tangentOnCurve
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def tangentOnCurve(self ,param = 0.5 ,normalize = 1 ):
'''
This function computes the tangent at the given parameter along the curve
@type param : float
@param param : At what value along the curve to sample
@type normalize : bool
@param normalize : whether or not to normalize the output tangent
@return Vector
'''
order = self.degree + 1
pos = Vector([0,0,0])
#methodA
for i in range(len(cp)-1) :
#First compute the basis
basis = bsplineBasis(self.knots ,i+1,order-1 , param)
#Then compute the Q parameter which is the derivative multiplier based on the -1 +1 control points
q = Vector((degree /(self.knots[i+degree +1] - self.knots[i+1])) * (self.controlPoints[i+1] - self.controlPoints[i]))
pos+= (basis*q)
if normalize == 1 :
return pos.normalize()
else :
return pos
示例4: test_magnitude_and_normalize
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def test_magnitude_and_normalize():
"""Quiz 2 calculating magnitude and normalization of Vectors"""
vector1 = Vector([-0.221, 7.437])
answer1 = Decimal('7.440')
assert round(vector1.magnitude(), 3) == answer1
vector2 = Vector([8.813, -1.331, -6.247])
answer2 = Decimal('10.884')
assert round(vector2.magnitude(), 3) == answer2
vector3 = Vector([5.581, -2.136])
answer3 = Vector([0.934, -0.357]).round_coords(3)
assert vector3.normalize().round_coords(3) == answer3
vector4 = Vector([1.996, 3.108, -4.554])
answer4 = Vector([0.340, 0.530, -0.777]).round_coords(3)
assert vector4.normalize().round_coords(3) == answer4
示例5: train
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def train():
print
print "---Training---"
print
queryUser()
my_vector = Vector()
s = Song(root,mode,title)
for i in range(num_measures):
# Generate a vector and build a measure from it.
training_vector = Vector("user")
s.addMeasure(training_vector)
s.playMeasure(title,i)
# Get feedback
user_opinion = raw_input("What did you think of that measure? (scale from 0-10): ")
while user_opinion.isdigit() == False or int(user_opinion) < 0 or int(user_opinion) > 10:
print "Invalid Response (please select a number from 0-10)"
user_opinion = raw_input("What did you think of that measure? (scale from 0-10): ")
user_opinion = int(user_opinion)
training_vector = s.measures[i].getVector() # update in the case that we repeated
my_vector.update(training_vector,.2,user_opinion)
# Get opinion on whole song
print "Here is your song!\n"
s.playSong()
song_opinion = int(raw_input("How much did you like that song? (scale from 0-10): "))
while song_opinion < 0 or song_opinion > 10:
print "Please enter an integer between 0 and 10: "
song_opinion = raw_input("How much did you like that song? (scale from 0-10): ")
while song_opinion.isdigit() != False or int(song_opinion) < 0 or int(song_opinion) > 10:
print "Invalid Response (please select a number from 0-10)"
song_opinion = raw_input("How much did you like that song? (scale from 0-10): ")
song_opinion = int(song_opinion)
# Update master based on user opinion
master = Vector("master")
master.update(my_vector,.05,song_opinion)
master.normalize()
master.writeToFile(".master.vct")
if user_opinion > 6 and num_measures > 7:
my_vector.writeToFile(".user_vectors.vct")
示例6: update
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def update(self, mines):
mines = sorted(mines, key = lambda m: m.position.distance(self.position))
# closest mine
closest_mine = mines[0]
# look_at vector
look_at = Vector(self.position.x - closest_mine.position.x,
self.position.y - closest_mine.position.y)
look_at.normalize()
outputs = self.neural_net.update([look_at.x, look_at.y,
self.bearing.x, self.bearing.y])
# rotation
self.rotation += (outputs[0] - outputs[1]) * 0.01
# speed
self.speed = outputs[2]
# calcuate new bearing
degrees = self.rotation * 180 / math.pi
self.bearing.x = -math.sin(degrees)
self.bearing.y = math.cos(degrees)
# calculate new position
self.position.x += self.bearing.x * self.speed
self.position.y += self.bearing.y * self.speed
if self.position.x > WIDTH: self.position.x = 0
if self.position.x < 0: self.position.x = WIDTH
if self.position.y > HEIGHT: self.position.y = 0
if self.position.y < 0: self.position.y = HEIGHT
return closest_mine
示例7: move
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def move(self, directions, *args):
""" Move around in 3D space using the keyboard.
Takes an array containing X , Y and Z axis directions.
Directions must be either 1, -1 or 0."""
acceleration = args[0]
direction = Vector(directions)
if direction.norm():
direction = direction.normalize() * self._speed
self._velocity = self._velocity + acceleration
# Calculate new position
movementDir = self._velocity + direction
movement = movementDir.get_value()
self._xPos += movement[0]
self._yPos += movement[1]
self._zPos += movement[2]
return movementDir
示例8: update
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
def update(self):
"""Update the hero sprite based on the user's iteraction.
Returns direction if the user touches the edge of the map
(i.e. "west" if user enters left edge of screen)
Returns None if the user doesn't exit the screen.
"""
#global solidGroup
if not self.tick():
return
x = 0
y = 0
# perform actions for each key press
pressed = pygame.key.get_pressed()
if pressed[K_SPACE]:
# drink a potion
if self.potions >= 1 and self.potiontimer == 0 and self.hp < self.hpmax:
sfxPlay("healed.wav")
self.potions -= 1
self.hp = self.hpmax
self.potiontimer = 1
if pressed[K_e]: # examined with 'E'
aoe = self.space_ahead()
for s in globalvars.solidGroup:
if aoe.colliderect(s.rect) and s.name is not self.name:
choice = s.examine()
if choice and isinstance(s, sprites.Transition):
return s.direction
break
if pressed[K_q]:
# drop a bomb
if self.bombs > 0 and self.bombtimer == 0:
self.bombs -= 1
globalvars.attackQ.add(Bomb(self))
self.bombtimer = 1
if pressed[K_a]: # left
x = -1
self.facing = "left"
self.moving = True
elif pressed[K_d]: # right
x = 1
self.facing = "right"
self.moving = True
if pressed[K_w]: # up
y = -1
self.facing = "back"
self.moving = True
elif pressed[K_s]: # down
y = 1
self.facing = "front"
self.moving = True
# perform actions for mouse buttons pressed
(mousebutton1, mousebutton2, mousebutton3) = pygame.mouse.get_pressed()
if mousebutton1 and self.weapon is not None:
self.mattack()
if mousebutton3 and self.gun is not None:
self.rattack()
# update movement rectangle
vect = Vector(x, y)
moveval = self.move(vect.normalize())
# finalize
self.animate()
return moveval
示例9: Car
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
#.........这里部分代码省略.........
self.last_ground = self.position
def move(self, new_position):
"""move the car"""
path = bresenham(self.position, new_position)
for i, c in enumerate(path):
if not self.state.aerial: # a flying car can move over anything
if self.race.track.type(c, hit=True) is WALL:
# hit a wall
if i == 0:
# car is stuck in a wall
return self.lakitu()
else:
# the car bounces against the wall
if path[i - 1][0] != c[0]:
self.set_speed(Vector(-0.5 * self.speed.x, 0.5 * self.speed.y))
else:
self.set_speed(Vector(0.5 * self.speed.x, -0.5 * self.speed.y))
new_position = self.position # do not move
break
if not self.state.jump:
if self.race.track.type(c) is DEEP:
# car is in a hole
return self.lakitu()
if self.racer.item is ITEMS[0] and self.race.track.type(c, special=True) is ITEM:
# the car touched an item block
block = self.race.track.item_blocks[(c[0], c[1])] # find the block that was touched
if not block.delay:
block.activate()
self.racer.get_item()
if self.race.track.type(c) is JUMP:
# touch a bumper
if self.speed.norm() < 100:
self.set_speed(self.speed.normalize(100.0))
self.state.change(aerial=1.0)
if self.race.track.type(c) is BOOST and self.speed.norm() < 300.0:
# touch a booster
self.set_speed(self.speed.normalize(300.0))
self.set_position(new_position)
def stop(self):
"""stops the car by killing its speed"""
self.set_speed(Vector(0.0, 0.0))
def set_speed(self, new_speed):
"""changes the speed of the car"""
self.speed = new_speed
def get_direction_vector(self):
"""returns the orientation of the car as a unit vector"""
return Vector(math.cos(self.direction), math.sin(self.direction))
def set_direction(self, new_direction):
"""changes the orientation of the car"""
self.direction = new_direction % (2 * math.pi)
self.sprite.image = self.choose_sprite() # update the sprite of the car
def collision(self, car):
"""simulate an elastic collision between two cars"""
direction_p = (car.position - self.position).normalize(1.0)
direction_o = Vector(-direction_p.y, direction_p.x)
u1p, u1o = self.speed * direction_p, self.speed * direction_o
u2p, u2o = car.speed * direction_p, car.speed * direction_o
if u1p > u2p:
m1, m2 = self.mass(), car.mass()
v1p = (u1p * (m1 - m2) + 2 * m2 * u2p) / (m1 + m2)
示例10: Segment
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
class Segment(object):
"""
A segment described by 2 vectors: the starting point and the direction/length vector.
"""
def __init__(self, point, direction):
self.start = Vector(point, copy=False)
self.direction = Vector(direction, copy=False)
def rotate_point(self, point, angle):
"""
Rotates the point around this segment with <angle> radians.
Returns the resulting new point.
Examples:
>>> x = Segment("1,1,1", "1,1,1")
>>> x.rotate_point("2, 2, 2", 10).is_same([2, 2, 2])
True
>>> x.rotate_point([1, 0, 0], 2 * math.pi/3).is_same([0, 1, 0])
True
>>> x.rotate_point([1, 0, 0], -2 * math.pi/3).is_same([0, 0, 1])
True
>>> y = Segment([0, 0, 0], [0, 1, 0])
>>> y.rotate_point([1, 0, 0], math.pi / 2).is_same([0, 0, -1])
True
>>> y.rotate_point([1, 0, 0], -math.pi / 2).is_same([0, 0, 1])
True
"""
normal = self.direction.assure_normal(error_message="Can't rotate around a 0 length segment")
point = Vector(point, copy=False)
sina = math.sin(angle)
cosa = math.cos(angle)
if np.allclose(sina, 0) and np.allclose(cosa, 1):
# this is a shortcut worth making, to get the exact same point for angles 2n*PI
return point
ap = point - self.start
x = normal.cross(ap)
cosdot = ap.dot(normal) * (1 - cosa)
return self.start + (cosa * ap) + (cosdot * normal) + (sina * x)
def normalize(self):
"""
Normalizes the direction vector, resulting in a norm 1 segment with the same start point.
"""
self.direction.normalize()
return self
def normal_plane(self):
"""
Returns the Plane which contains the start point and it is normal to the direction.
>>> x = Segment("1,1,1", "1,1,1")
>>> n = math.sqrt(3)
>>> x.normal_plane().is_same(Plane([1/n, 1/n, 1/n], n))
True
>>> y = Segment([0, 0, 0], [0, 1, 0])
>>> y.normal_plane().is_same(Plane("0, 1, 0", 0))
True
"""
normal = self.direction.assure_normal(error_message="Can't have a normal plane for a 0 length segment")
return Plane(normal.copy(), normal.dot(self.start))
def is_same(self, other, rtol=1.e-5, atol=1.e-8):
start_same = self.start.is_same(other.start, rtol=rtol, atol=atol)
dir_same = self.direction.is_same(other.direction, rtol=rtol, atol=atol)
return start_same and dir_same
def __repr__(self):
return "Segment({0}, {1})".format(self.start, self.direction)
def __iter__(self):
for x in self.start:
yield x
for x in self.direction:
yield x
示例11: Fish
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
class Fish(pygame.sprite.Sprite):
def __init__(self):
self.unflipped = pygame.image.load('img/fish_happy.png').convert_alpha()
self.flipped = pygame.transform.flip(self.unflipped, True, False)
self.unflipped_sad = pygame.image.load('img/fish_sad.png').convert_alpha()
self.unflipped_sad = pygame.transform.flip(self.unflipped_sad, False, True)
self.flipped_sad = pygame.transform.flip(self.unflipped_sad, True, False)
self.image = self.unflipped
self.rect = self.image.get_rect()
self.direction = Vector(3,1)
self.position = Vector(0, 0)
self.MAX_ANGLE = math.pi/16
self.speed = self._speed = random.randint(1, 3)
self.delay = 0
self._dead = False
self.randomize_direction()
@property
def dead(self):
return self._dead
@dead.setter
def dead(self, isDead):
self._dead = isDead
if isDead:
self.speed = random.uniform(0.1, 0.5)
else:
self.speed = self._speed
def set_direction(self, x, y):
self.direction = Vector(x, y)
def randomize_direction(self):
random_angle = random.uniform(-self.MAX_ANGLE, self.MAX_ANGLE)
self.direction = self.direction.rotate(random_angle).normalize()
def move(self, dx, dy):
self.position += Vector(dx, dy)
def general_direction(self):
deg = math.degrees(self.direction.angle)
while deg < 0:
deg += 360
if deg > 90 and deg < 270:
return Vector(-1, 0)
else:
return Vector(1, 0)
def update(self, bounds):
if bounds.height <= self.rect.height:
self.direction = self.general_direction()
self.position = self.position.set_y(bounds.bottom - self.rect.height)
if self.delay != 0:
self.delay -= 1
return # Quit early
else:
direction_step = self.direction.normalize(self.speed)
self.position += direction_step
self.rect.top = round(self.position.y)
self.rect.left = round(self.position.x)
# Check top bound
if self.rect.top < bounds.top and bounds.height > self.rect.height:
self.position = self.position.set_y(bounds.top)
self.randomize_direction()
self.direction = self.direction.set_y(abs(self.direction.y))
# Check bottom bound
if self.rect.bottom > bounds.bottom and bounds.height > self.rect.height:
self.position = self.position.set_y(bounds.bottom - self.rect.height)
self.direction = self.direction.set_y(-abs(self.direction.y))
self.randomize_direction()
# Check right and left bound
if self.rect.left > bounds.right or self.rect.right < bounds.left:
if bounds.height < self.rect.height:
self.position = self.position.set_y(bounds.bottom - self.rect.height)
else:
self.position = self.position.set_y(random.randint(bounds.top, bounds.bottom - self.rect.height))
self.position = self.position.set_x(random.choice([bounds.left-self.rect.width, bounds.right]))
# Flip direction depending on what edge we're at
if self.position.x == -self.rect.width:
self.direction = Vector(1, 0)
else:
self.direction = Vector(-1, 0)
#.........这里部分代码省略.........
示例12: Lion
# 需要导入模块: from vector import Vector [as 别名]
# 或者: from vector.Vector import normalize [as 别名]
class Lion(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self,self.groups)
self.speed = 25 * 4
self.makeImages()
self.index = 0
self.image = self.lions[self.index]
self.rect = self.image.get_rect()
self.Vp = Vector(300,500)
self.setPosition()
def setPosition(self):
self.rect.center = tuple(self.Vp)
def makeImages(self):
folder = '../../data'
spritesheet = pygame.image.load( os.path.join(folder,'char9.bmp') )
self.lions = list()
w,h = 127,127
for no in range(4): # first line contains 4 lions
self.lions.append( spritesheet.subsurface( (127*no,64,w,h)) )
for no in range(2):
self.lions.append( spritesheet.subsurface( (127*no,262-64,w,h) ) )
self.lions1= list()
for lion in self.lions:
lion1 = pygame.transform.scale(lion,(100,100))
lion1.set_colorkey(black)
lion1 = lion1.convert_alpha()
self.lions1.append(lion1)
self.lions = self.lions1[:]
def getdiffAngle(self,player):
if player is None: return
delta = player.Vp - self.Vp
targetAngle = atan2(-delta.y,delta.x)/pi * 180
diffAngle = targetAngle - self.tankAngle
if diffAngle < 0: diffAngle += 360
diffAngle %= 360
return diffAngle
def calculateDirection(self):
mousepos = pygame.mouse.get_pos()
self.Vd = Vector(mousepos) - self.Vp
self.Vd.normalize()
def move(self,seconds):
self.calculateDirection()
self.Vp += self.Vd * self.speed * seconds
self.index += 1
self.index %= 6
self.image = self.lions[self.index]
self.setPosition()
def stop(self):
self.index = 0
self.image = self.lions[self.index]
self.setPosition()
def update(self,seconds):
left_mouse_pressed = pygame.mouse.get_pressed()[0]
if left_mouse_pressed:
self.move(seconds)