How to move an object using keyboard events in Python? #4730
-
Hello everyone, I created an object and then I want to make it move through keyboard events. I try to use the keyboard to update T_epm_sim to move the object in the direction that updates the object's position, but the object does not move in the scene. I don't know how to see objects moving in the scene, please help me. The code to create the object is as follows:
The code to control movement is as follows:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @zhilengqilaiya import sys
import Sofa
class MoveRigidParticles(Sofa.Core.Controller):
def __init__(self, *args, **kwargs):
# These are needed (and the normal way to override from a python class)
Sofa.Core.Controller.__init__(self, *args, **kwargs)
self.RigidBody = kwargs.get("RigidBody")
def onKeypressedEvent(self, event):
key = event['key']
if key=="+" :
with self.RigidBody.position.writeableArray() as wa:
wa[0][0] += 0.01
if key=="-" :
with self.RigidBody.position.writeableArray() as wa:
wa[0][0] -= 0.01
return 0;
def createScene(root):
root.gravity=[0, 0, 0]
root.name="root"
root.dt=0.01
root.addObject('RequiredPlugin', name="loadSOFAModules", pluginName="Sofa.Component.LinearSolver.Iterative Sofa.Component.Mass Sofa.Component.StateContainer Sofa.Component.ODESolver.Backward")
root.addObject('DefaultAnimationLoop', computeBoundingBox=True)
root.bbox=[[-1,-1,-1],[1,1,1]]
Particle = root.addChild('Particle0')
Particle.addObject('EulerImplicitSolver')
Particle.addObject('CGLinearSolver', threshold='1e-09', tolerance='1e-09', iterations='200')
Particle.addObject('MechanicalObject', showObject='1', position='0 0 0 0 0 0 1', name='RigidBody', template='Rigid3d')
Particle.addObject('UniformMass', totalMass='1')
root.addObject( MoveRigidParticles(name="MyRigidController", RigidBody=Particle.RigidBody) )
return 0;
def main():
import SofaRuntime
import Sofa.Gui
# Make sure to load all SOFA libraries
SofaRuntime.importPlugin("SofaBaseMechanics")
SofaRuntime.importPlugin("SofaOpenglVisual")
SofaRuntime.importPlugin("CImgPlugin")
#Create the root node
root = Sofa.Core.Node("root")
# Call the below 'createScene' function to create the scene graph
createScene(root)
Sofa.Simulation.init(root)
# Launch the GUI (qt or qglviewer)
Sofa.Gui.GUIManager.Init("myscene", "qglviewer")
Sofa.Gui.GUIManager.createGUI(root, __file__)
Sofa.Gui.GUIManager.SetDimension(1080, 1080)
# Initialization of the scene will be done here
Sofa.Gui.GUIManager.MainLoop(root)
Sofa.Gui.GUIManager.closeGUI()
print("Simulation is done.")
# Function used only if this script is called from a python environment
if __name__ == '__main__':
main() |
Beta Was this translation helpful? Give feedback.
Hi @zhilengqilaiya
Here is a script to move (translate along x) a rigid frame: