世界上最早的鼠标诞生于1964年,它是由美国人道格·恩格尔巴特(Doug Engelbart)发明的。IEEE协会把鼠标的发明列为计算机诞生50年来最重大的事件之一,可见其对IT历程的重大影响作用。1983年苹果公司给自家的电脑安上了鼠标,用户就开始离不开这个小东西了。而现代游戏,离开了鼠标,99%的都没法玩!我们自然得好好研究如何使用鼠标来操控我们的游戏。
在3D游戏中,可以使用鼠标来控制视角。这种时候,我们不使用鼠标的位置,因为鼠标可能会跑到窗口外面,我们使用鼠标现在与上一帧的相对偏移量。在下面的例子中,我们演示使用鼠标的左右移动来转动我们熟悉的小鱼
background_image_filename = './img/Underwater.png'
sprite_image_filename = './img/fish-b.png'
import pygame
from pygame.locals import *
from sys import exit
from Vec2d import *
from math import *
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()
# 让pygame完全控制鼠标start
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
# 让pygame完全控制鼠标end
clock = pygame.time.Clock()
sprite_pos = Vec2d(200, 150)
sprite_speed = 300.
sprite_rotation = 0.
sprite_rotation_speed = 360.
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
#完全控制鼠标,这样鼠标的光标看不见,也不会跑到pygame窗口外面去所以你得准备一句代码来退出程序。
# 按Esc则退出游戏
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
pressed_keys = pygame.key.get_pressed()
# 这里获取鼠标的按键情况
pressed_mouse = pygame.mouse.get_pressed()
rotation_direction = 0.
movement_direction = 0.
# 获得x方向上的偏移量,计算转动,除以5是把动作放慢一点
rotation_direction = pygame.mouse.get_rel()[0]/5.0
if pressed_keys[K_LEFT]:
rotation_direction = +1.
if pressed_keys[K_RIGHT]:
rotation_direction = -1.
# 多了一个鼠标左键按下的判断
if pressed_keys[K_UP] or pressed_mouse[0]:
movement_direction = +1.
# 多了一个鼠标右键按下的判断
if pressed_keys[K_DOWN] or pressed_mouse[2]:
movement_direction = -1.
screen.blit(background, (0,0))
rotated_sprite = pygame.transform.rotate(sprite, sprite_rotation)
w, h = rotated_sprite.get_size()
sprite_draw_pos = Vec2d(sprite_pos.x-w/2, sprite_pos.y-h/2)
screen.blit(rotated_sprite, sprite_draw_pos)
time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.0
sprite_rotation += rotation_direction * sprite_rotation_speed * time_passed_seconds
heading_y = sin(sprite_rotation*pi/180.)
heading_x = cos(sprite_rotation*pi/180.)
heading = Vec2d(heading_x, heading_y)
heading *= movement_direction
sprite_pos+= heading * sprite_speed * time_passed_seconds
pygame.display.update()
pygame.mouse的函数:
pygame.mouse.get_pressed —— 返回按键按下情况,返回的是一元组,分别为(左键, 中键, 右键),如按下则为True
pygame.mouse.get_rel —— 返回相对偏移量,(x方向, y方向)的一元组
pygame.mouse.get_pos —— 返回当前鼠标位置(x, y)
pygame.mouse.set_pos —— 显而易见,设置鼠标位置
pygame.mouse.set_visible —— 设置鼠标光标是否可见
pygame.mouse.get_focused —— 如果鼠标在pygame窗口内有效,返回True
pygame.mouse.set_cursor —— 设置鼠标的默认光标式样,是不是感觉我们以前做的事情白费了?哦不会,我们使用的方法有着更好的效果。
pyGame.mouse.get_cursor —— 不再解释。
本站内容未经许可,禁止任何网站及个人进行转载。



