Найти - Пользователи
Полная версия: Не могу разобраться с API BlenderGameEngine, с импортом библиотек.
Начало » Python для новичков » Не могу разобраться с API BlenderGameEngine, с импортом библиотек.
1
rudm
Установлен Blender 2.59.
Пытаюсь запустить простой скрипт движения камеры по движению мышки.
# Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement MouseLook::
# To use a mouse movement sensor "Mouse" and a
# motion actuator to mouse look:
import bge.render
import bge.logic

# scale sets the speed of motion
scale = 1.0, 0.5

co = bge.logic.getCurrentController()
obj = co.getOwner()
mouse = co.getSensor("Mouse")
lmotion = co.getActuator("LMove")
wmotion = co.getActuator("WMove")

# Transform the mouse coordinates to see how far the mouse has moved.
def mousePos():
x = (bge.render.getWindowWidth() / 2 - mouse.getXPosition()) * scale[0]
y = (bge.render.getWindowHeight() / 2 - mouse.getYPosition()) * scale[1]
return (x, y)

pos = mousePos()

# Set the amount of motion: X is applied in world coordinates...
lmotion.setTorque(0.0, 0.0, pos[0], False)
# ...Y is applied in local coordinates
wmotion.setTorque(-pos[1], 0.0, 0.0, True)

# Activate both actuators
bge.logic.addActiveActuator(lmotion, True)
bge.logic.addActiveActuator(wmotion, True)

# Centre the mouse
bge.render.setMousePosition(bge.render.getWindowWidth() / 2, bge.render.getWindowHeight() / 2)
И имею ошибку Import Error: No module named render. Хотя согласно справки по API
с оф.сайта, должно работать. Не могу понять в чем проблема. Если кто то сталкивался, то буду благодарен за любую помощь, сам уже весь мозг сломал. В системе стоит еще Python 2.6.3, но ведь эта версия Blender использует свой, встроенный Python насколько я знаю. Или может быть проблема в системных настройках и в том, что по умолчанию у меня установлен старый Python 2.6.3 и Blender пытается обрабатывать скрипты через него? В общем, буду благодарен за любую помощь, уже не знаю куда обратится просто.
yrttyr
Уверен, что апи в справке для 2.59?
Лучше спросить на сайте про блендер http://blender3d.org.ua/
rudm
Да я уже даже с родного сайта пример пробовал.
http://www.blender.org/documentation/blender_python_api_2_59_release/bge.render.html#
как раз справка по API моей версии. То же самое.
Я там уже спросил, но там в основном люди которые моделированием занимаются, а не API.
Попробую удалить Python 2.6.3, вдруг поможет.
sp3
Попробуйте просто
import bge

если не найдет модуль
import sys
sys.path.append(r'путь до bge')
rudm
Благодарю! Модуль нашел, теперь уже какие то более вменяемые ошибки выдает:
“KX_Camera object is not callable”, хотя почему он не может к камере обратится, странно. Большое вам спасибо за ответы.
Вдруг кому то пригодится: Вот тут решение, частичное.
http://blenderartists.org/forum/archive/index.php/t-165246.html
Как я понял теперь свойства хранятся и задаются в массивах а не так как в ранних версиях.

# Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement MouseLook::
# To use a mouse movement sensor "Mouse" and a
# motion actuator to mouse look:
import bge

# scale sets the speed of motion
scale = [1.0, 0.5]

cont = bge.logic.getCurrentController()
obj = cont.owner

mouse = cont.sensors["Mouse"]

lmotion = cont.actuators["LMove"]
wmotion = cont.actuators["WMove"]

# Transform the mouse coordinates to see how far the mouse has moved.
def mousePos():
x = (bge.render.getWindowWidth() / 2 - mouse.getXPosition()) * scale[0]
y = (bge.render.getWindowHeight() / 2 - mouse.getYPosition()) * scale[1]
return (x, y)

pos = mousePos()

# Set the amount of motion: X is applied in world coordinates...
lmotion.setTorque(0.0, 0.0, pos[0], False)
# ...Y is applied in local coordinates
wmotion.setTorque(-pos[1], 0.0, 0.0, True)

# Activate both actuators
bge.logic.addActiveActuator(lmotion, True)
bge.logic.addActiveActuator(wmotion, True)

# Centre the mouse
bge.render.setMousePosition(bge.render.getWindowWidth() / 2, bge.render.getWindowHeight() / 2)
Теперь уже ошибки касаются неправильно названных свойств
SCA_Mouse_Sensor Object has no attribute getXPosition
но это наверное просто поправить посмотрев в справку по API.

Более менее поправил
# Example Uses an L{SCA_MouseSensor}, and two L{KX_ObjectActuator}s to implement MouseLook::
# To use a mouse movement sensor "Mouse" and a
# motion actuator to mouse look:
import bge

# scale sets the speed of motion
scale = [1.0, 0.5]

cont = bge.logic.getCurrentController()
obj = cont.owner

mouse = cont.sensors["Mouse"]

lmotion = cont.actuators["LMove"]
wmotion = cont.actuators["WMove"]

# Transform the mouse coordinates to see how far the mouse has moved.
def mousePos():
x = (bge.render.getWindowWidth() / 2 - mouse.position[0] * scale[0]
y = (bge.render.getWindowHeight() / 2 - mouse.position[1] * scale[1]
return (x, y)

pos = mousePos()

# Set the amount of motion: X is applied in world coordinates...
lmotion.setTorque(0.0, 0.0, pos[0], False)
# ...Y is applied in local coordinates
wmotion.setTorque(-pos[1], 0.0, 0.0, True)

# Activate both actuators
bge.logic.addActiveActuator(lmotion, True)
bge.logic.addActiveActuator(wmotion, True)

# Centre the mouse
bge.render.setMousePosition(bge.render.getWindowWidth() / 2, bge.render.getWindowHeight() / 2)
Если верить справке по API, то теперь координаты мыши хранятся тоже в массиве,
но почему то при обращении ко второму элементу массива
y = (bge.render.getWindowHeight() / 2 - mouse.position[1] * scale[1]
Получаю ошибку. Syntax Error: Invalid Syntax. Странно. Может быть в Python 3.0 по другому как то надо обращаться к элементам массива?
sp3
У вас скобка не закрыта.

С bge незнаком, но думаю документацию смотреть лучше не любую, а к версии, которая у вас установлена.
rudm
Вот я слепошарый, простите. Благодарю. Да я как раз и смотрю документацию по моей версии, но они видимо файлы примеров поменяли везде, под версию 2.60 уже.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB