Loading...
Searching...
No Matches
Tutorial 19: Mouse and Joystick

This tutorial builds on example 04.Movement which showed how to handle keyboard events in Irrlicht. Here we'll handle mouse events and joystick events, if you have a joystick connected and a device that supports joysticks. These are currently Windows, Linux and SDL devices.

#ifdef _MSC_VER
// We'll define this to stop MSVC complaining about sprintf().
#define _CRT_SECURE_NO_WARNINGS
#pragma comment(lib, "Irrlicht.lib")
#endif
#include <irrlicht.h>
#include "driverChoice.h"
using namespace irr;
driverChoice.h
irrlicht.h
Main header file of the irrlicht, the only file needed to include.
irr
Everything in the Irrlicht Engine can be found in this namespace.
Definition aabbox3d.h:13

Just as we did in example 04.Movement, we'll store the latest state of the mouse and the first joystick, updating them as we receive events.

class MyEventReceiver : public IEventReceiver
{
public:
// We'll create a struct to record info on the mouse state
struct SMouseState
{
core::position2di Position;
bool LeftButtonDown;
SMouseState() : LeftButtonDown(false) { }
} MouseState;
// This is the one method that we have to implement
virtual bool OnEvent(const SEvent& event)
{
// Remember the mouse state
if (event.EventType == irr::EET_MOUSE_INPUT_EVENT)
{
switch(event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
MouseState.LeftButtonDown = true;
break;
case EMIE_LMOUSE_LEFT_UP:
MouseState.LeftButtonDown = false;
break;
case EMIE_MOUSE_MOVED:
MouseState.Position.X = event.MouseInput.X;
MouseState.Position.Y = event.MouseInput.Y;
break;
default:
// We won't use the wheel
break;
}
}
// The state of each connected joystick is sent to us
// once every run() of the Irrlicht device. Store the
// state of the first joystick, ignoring other joysticks.
// This is currently only supported on Windows and Linux.
if (event.EventType == irr::EET_JOYSTICK_INPUT_EVENT
&& event.JoystickEvent.Joystick == 0)
{
JoystickState = event.JoystickEvent;
}
return false;
}
const SEvent::SJoystickEvent & GetJoystickState(void) const
{
return JoystickState;
}
const SMouseState & GetMouseState(void) const
{
return MouseState;
}
MyEventReceiver()
{
}
private:
SEvent::SJoystickEvent JoystickState;
};
irr::IEventReceiver
Interface of an object which can receive events.
Definition IEventReceiver.h:434
irr::core::position2di
vector2d< s32 > position2di
Definition position2d.h:24
irr::EMIE_LMOUSE_LEFT_UP
@ EMIE_LMOUSE_LEFT_UP
Left mouse button was left up.
Definition IEventReceiver.h:86
irr::EMIE_LMOUSE_PRESSED_DOWN
@ EMIE_LMOUSE_PRESSED_DOWN
Left mouse button was pressed down.
Definition IEventReceiver.h:77
irr::EMIE_MOUSE_MOVED
@ EMIE_MOUSE_MOVED
The mouse cursor changed its position.
Definition IEventReceiver.h:95
irr::EET_MOUSE_INPUT_EVENT
@ EET_MOUSE_INPUT_EVENT
A mouse input event.
Definition IEventReceiver.h:30
irr::EET_JOYSTICK_INPUT_EVENT
@ EET_JOYSTICK_INPUT_EVENT
A joystick (joypad, gamepad) input event.
Definition IEventReceiver.h:45
irr::SEvent::SJoystickEvent::Joystick
u8 Joystick
The ID of the joystick which generated this event.
Definition IEventReceiver.h:381
irr::SEvent::SMouseInput::Event
EMOUSE_INPUT_EVENT Event
Type of mouse event.
Definition IEventReceiver.h:312
irr::SEvent::JoystickEvent
struct SJoystickEvent JoystickEvent
Definition IEventReceiver.h:420
irr::SEvent::MouseInput
struct SMouseInput MouseInput
Definition IEventReceiver.h:418
irr::SEvent::EventType
EEVENT_TYPE EventType
Definition IEventReceiver.h:414

The event receiver for keeping the pressed keys is ready, the actual responses will be made inside the render loop, right before drawing the scene. So lets just create an irr::IrrlichtDevice and the scene node we want to move. We also create some other additional scene nodes, to show that there are also some different possibilities to move and animate scene nodes.

int main()
{
// ask user for driver
video::E_DRIVER_TYPE driverType=driverChoiceConsole();
if (driverType==video::EDT_COUNT)
return 1;
// create device
MyEventReceiver receiver;
IrrlichtDevice* device = createDevice(driverType,
core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver);
if (device == 0)
return 1; // could not create selected driver.
core::array<SJoystickInfo> joystickInfo;
if(device->activateJoysticks(joystickInfo))
{
std::cout << "Joystick support is enabled and " << joystickInfo.size() << " joystick(s) are present." << std::endl;
for(u32 joystick = 0; joystick < joystickInfo.size(); ++joystick)
{
std::cout << "Joystick " << joystick << ":" << std::endl;
std::cout << "\tName: '" << joystickInfo[joystick].Name.c_str() << "'" << std::endl;
std::cout << "\tAxes: " << joystickInfo[joystick].Axes << std::endl;
std::cout << "\tButtons: " << joystickInfo[joystick].Buttons << std::endl;
std::cout << "\tHat is: ";
switch(joystickInfo[joystick].PovHat)
{
case SJoystickInfo::POV_HAT_PRESENT:
std::cout << "present" << std::endl;
break;
case SJoystickInfo::POV_HAT_ABSENT:
std::cout << "absent" << std::endl;
break;
case SJoystickInfo::POV_HAT_UNKNOWN:
default:
std::cout << "unknown" << std::endl;
break;
}
}
}
else
{
std::cout << "Joystick support is not enabled." << std::endl;
}
core::stringw tmp = L"Irrlicht Joystick Example (";
tmp += joystickInfo.size();
tmp += " joysticks)";
device->setWindowCaption(tmp.c_str());
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
irr::IrrlichtDevice
The Irrlicht device. You can create it with createDevice() or createDeviceEx().
Definition IrrlichtDevice.h:44
irr::IrrlichtDevice::setWindowCaption
virtual void setWindowCaption(const wchar_t *text)=0
Sets the caption of the window.
irr::IrrlichtDevice::getSceneManager
virtual scene::ISceneManager * getSceneManager()=0
Provides access to the scene manager.
irr::IrrlichtDevice::getVideoDriver
virtual video::IVideoDriver * getVideoDriver()=0
Provides access to the video driver for drawing 3d and 2d geometry.
irr::IrrlichtDevice::activateJoysticks
virtual bool activateJoysticks(core::array< SJoystickInfo > &joystickInfo)=0
Activate any joysticks, and generate events for them.
irr::core::array
Self reallocating template array (like stl vector) with additional features.
Definition irrArray.h:23
irr::core::array::size
u32 size() const
Get number of occupied elements of the array.
Definition irrArray.h:368
irr::core::dimension2d
Specifies a 2 dimensional size.
Definition dimension2d.h:21
irr::core::string::c_str
const T * c_str() const
Returns character string.
Definition irrString.h:495
irr::scene::ISceneManager
The Scene Manager manages scene nodes, mesh recources, cameras and all the other stuff.
Definition ISceneManager.h:151
irr::video::IVideoDriver
Interface to driver which is able to perform 2d and 3d graphics functions.
Definition IVideoDriver.h:257
irr::core::stringw
string< wchar_t > stringw
Typedef for wide character strings.
Definition irrString.h:1361
irr::video::E_DRIVER_TYPE
E_DRIVER_TYPE
An enum for all types of drivers the Irrlicht Engine supports.
Definition EDriverTypes.h:15
irr::video::EDT_COUNT
@ EDT_COUNT
No driver, just for counting the elements.
Definition EDriverTypes.h:56
irr::u32
unsigned int u32
32 bit unsigned variable.
Definition irrTypes.h:58
irr::createDevice
IRRLICHT_API IrrlichtDevice *IRRCALLCONV createDevice(video::E_DRIVER_TYPE deviceType=video::EDT_SOFTWARE, const core::dimension2d< u32 > &windowSize=(core::dimension2d< u32 >(640, 480)), u32 bits=16, bool fullscreen=false, bool stencilbuffer=false, bool vsync=false, IEventReceiver *receiver=0)
Creates an Irrlicht device. The Irrlicht device is the root object for using the engine.
irr::SJoystickInfo::POV_HAT_UNKNOWN
@ POV_HAT_UNKNOWN
The presence or absence of a hat cannot be determined.
Definition IEventReceiver.h:482
irr::SJoystickInfo::POV_HAT_ABSENT
@ POV_HAT_ABSENT
A hat is definitely not present.
Definition IEventReceiver.h:479
irr::SJoystickInfo::POV_HAT_PRESENT
@ POV_HAT_PRESENT
A hat is definitely present.
Definition IEventReceiver.h:476

We'll create an arrow mesh and move it around either with the joystick axis/hat, or make it follow the mouse pointer.

scene::ISceneNode * node = smgr->addMeshSceneNode(
smgr->addArrowMesh( "Arrow",
video::SColor(255, 255, 0, 0),
video::SColor(255, 0, 255, 0),
16,16,
2.f, 1.3f,
0.1f, 0.6f
)
);
node->setMaterialFlag(video::EMF_LIGHTING, false);
scene::ICameraSceneNode * camera = smgr->addCameraSceneNode();
camera->setPosition(core::vector3df(0, 0, -10));
// As in example 04, we'll use framerate independent movement.
u32 then = device->getTimer()->getTime();
const f32 MOVEMENT_SPEED = 5.f;
while(device->run())
{
// Work out a frame delta time.
const u32 now = device->getTimer()->getTime();
const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds
then = now;
bool movedWithJoystick = false;
core::vector3df nodePosition = node->getPosition();
if(joystickInfo.size() > 0)
{
f32 moveHorizontal = 0.f; // Range is -1.f for full left to +1.f for full right
f32 moveVertical = 0.f; // -1.f for full down to +1.f for full up.
const SEvent::SJoystickEvent & joystickData = receiver.GetJoystickState();
// We receive the full analog range of the axes, and so have to implement our
// own dead zone. This is an empirical value, since some joysticks have more
// jitter or creep around the center point than others. We'll use 5% of the
// range as the dead zone, but generally you would want to give the user the
// option to change this.
const f32 DEAD_ZONE = 0.05f;
moveHorizontal =
(f32)joystickData.Axis[SEvent::SJoystickEvent::AXIS_X] / 32767.f;
if(fabs(moveHorizontal) < DEAD_ZONE)
moveHorizontal = 0.f;
moveVertical =
(f32)joystickData.Axis[SEvent::SJoystickEvent::AXIS_Y] / -32767.f;
if(fabs(moveVertical) < DEAD_ZONE)
moveVertical = 0.f;
// POV hat info is only currently supported on Windows, but the value is
// guaranteed to be 65535 if it's not supported, so we can check its range.
const u16 povDegrees = joystickData.POV / 100;
if(povDegrees < 360)
{
if(povDegrees > 0 && povDegrees < 180)
moveHorizontal = 1.f;
else if(povDegrees > 180)
moveHorizontal = -1.f;
if(povDegrees > 90 && povDegrees < 270)
moveVertical = -1.f;
else if(povDegrees > 270 || povDegrees < 90)
moveVertical = +1.f;
}
if(!core::equals(moveHorizontal, 0.f) || !core::equals(moveVertical, 0.f))
{
nodePosition.X += MOVEMENT_SPEED * frameDeltaTime * moveHorizontal;
nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime * moveVertical;
movedWithJoystick = true;
}
}
// If the arrow node isn't being moved with the joystick, then have it follow the mouse cursor.
if(!movedWithJoystick)
{
// Create a ray through the mouse cursor.
core::line3df ray = smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(
receiver.GetMouseState().Position, camera);
// And intersect the ray with a plane around the node facing towards the camera.
core::plane3df plane(nodePosition, core::vector3df(0, 0, -1));
core::vector3df mousePosition;
if(plane.getIntersectionWithLine(ray.start, ray.getVector(), mousePosition))
{
// We now have a mouse position in 3d space; move towards it.
core::vector3df toMousePosition(mousePosition - nodePosition);
const f32 availableMovement = MOVEMENT_SPEED * frameDeltaTime;
if(toMousePosition.getLength() <= availableMovement)
nodePosition = mousePosition; // Jump to the final position
else
nodePosition += toMousePosition.normalize() * availableMovement; // Move towards it
}
}
node->setPosition(nodePosition);
// Turn lighting on and off depending on whether the left mouse button is down.
node->setMaterialFlag(video::EMF_LIGHTING, receiver.GetMouseState().LeftButtonDown);
driver->beginScene(true, true, video::SColor(255,113,113,133));
smgr->drawAll(); // draw the 3d scene
driver->endScene();
}
irr::ITimer::getTime
virtual u32 getTime() const =0
Returns current virtual time in milliseconds.
irr::IrrlichtDevice::run
virtual bool run()=0
Runs the device.
irr::IrrlichtDevice::getTimer
virtual ITimer * getTimer()=0
Provides access to the engine's timer.
irr::core::line3d::start
vector3d< T > start
Start point of line.
Definition line3d.h:130
irr::core::line3d::getVector
vector3d< T > getVector() const
Get vector of line.
Definition line3d.h:71
irr::core::vector3d::X
T X
X coordinate of the vector.
Definition vector3d.h:408
irr::core::vector3d::normalize
vector3d< T > & normalize()
Normalizes the vector.
Definition vector3d.h:168
irr::core::vector3d::Y
T Y
Y coordinate of the vector.
Definition vector3d.h:411
irr::scene::ICameraSceneNode
Scene Node which is a (controlable) camera.
Definition ICameraSceneNode.h:24
irr::scene::ISceneCollisionManager::getRayFromScreenCoordinates
virtual core::line3d< f32 > getRayFromScreenCoordinates(const core::position2d< s32 > &pos, ICameraSceneNode *camera=0)=0
Returns a 3d ray which would go through the 2d screen coodinates.
irr::scene::ISceneManager::drawAll
virtual void drawAll()=0
Draws all the scene nodes.
irr::scene::ISceneManager::getSceneCollisionManager
virtual ISceneCollisionManager * getSceneCollisionManager()=0
Get pointer to the scene collision manager.
irr::scene::ISceneManager::addMeshSceneNode
virtual IMeshSceneNode * addMeshSceneNode(IMesh *mesh, ISceneNode *parent=0, s32 id=-1, const core::vector3df &position=core::vector3df(0, 0, 0), const core::vector3df &rotation=core::vector3df(0, 0, 0), const core::vector3df &scale=core::vector3df(1.0f, 1.0f, 1.0f), bool alsoAddIfMeshPointerZero=false)=0
Adds a scene node for rendering a static mesh.
irr::scene::ISceneManager::addCameraSceneNode
virtual ICameraSceneNode * addCameraSceneNode(ISceneNode *parent=0, const core::vector3df &position=core::vector3df(0, 0, 0), const core::vector3df &lookat=core::vector3df(0, 0, 100), s32 id=-1, bool makeActive=true)=0
Adds a camera scene node to the scene graph and sets it as active camera.
irr::scene::ISceneManager::addArrowMesh
virtual IAnimatedMesh * addArrowMesh(const io::path &name, video::SColor vtxColorCylinder=0xFFFFFFFF, video::SColor vtxColorCone=0xFFFFFFFF, u32 tesselationCylinder=4, u32 tesselationCone=8, f32 height=1.f, f32 cylinderHeight=0.6f, f32 widthCylinder=0.05f, f32 widthCone=0.3f)=0
add a static arrow mesh to the meshpool
irr::scene::ISceneNode
Scene node interface.
Definition ISceneNode.h:41
irr::scene::ISceneNode::setPosition
virtual void setPosition(const core::vector3df &newpos)
Sets the position of the node relative to its parent.
Definition ISceneNode.h:507
irr::scene::ISceneNode::setMaterialFlag
void setMaterialFlag(video::E_MATERIAL_FLAG flag, bool newvalue)
Sets all material flags at once to a new value.
Definition ISceneNode.h:425
irr::scene::ISceneNode::getPosition
virtual const core::vector3df & getPosition() const
Gets the position of the node relative to its parent.
Definition ISceneNode.h:498
irr::video::IVideoDriver::beginScene
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true, SColor color=SColor(255, 0, 0, 0), const SExposedVideoData &videoData=SExposedVideoData(), core::rect< s32 > *sourceRect=0)=0
Applications must call this method before performing any rendering.
irr::video::IVideoDriver::endScene
virtual bool endScene()=0
Presents the rendered image to the screen.
irr::video::SColor
Class representing a 32 bit ARGB color.
Definition SColor.h:202
irr::core::vector3df
vector3d< f32 > vector3df
Typedef for a f32 3d vector.
Definition vector3d.h:445
irr::core::line3df
line3d< f32 > line3df
Typedef for an f32 line.
Definition line3d.h:136
irr::core::equals
bool equals(const f64 a, const f64 b, const f64 tolerance=ROUNDING_ERROR_f64)
returns if a equals b, taking possible rounding errors into account
Definition irrMath.h:185
irr::core::plane3df
plane3d< f32 > plane3df
Typedef for a f32 3d plane.
Definition plane3d.h:236
irr::video::EMF_LIGHTING
@ EMF_LIGHTING
Will this material be lighted? Default: true.
Definition EMaterialFlags.h:26
irr::f32
float f32
32 bit floating point variable.
Definition irrTypes.h:104
irr::u16
unsigned short u16
16 bit unsigned variable.
Definition irrTypes.h:40
irr::SEvent::SJoystickEvent
A joystick event.
Definition IEventReceiver.h:343
irr::SEvent::SJoystickEvent::Axis
s16 Axis[NUMBER_OF_AXES]
Definition IEventReceiver.h:369
irr::SEvent::SJoystickEvent::AXIS_X
@ AXIS_X
Definition IEventReceiver.h:348
irr::SEvent::SJoystickEvent::AXIS_Y
@ AXIS_Y
Definition IEventReceiver.h:349
irr::SEvent::SJoystickEvent::POV
u16 POV
Definition IEventReceiver.h:376

In the end, delete the Irrlicht device.

device->drop();
return 0;
}
irr::IReferenceCounted::drop
bool drop() const
Drops the object. Decrements the reference counter by one.
Definition IReferenceCounted.h:116
- Irrlicht Engine Documentation © 2003-2012 by Nikolaus Gebhardt. Generated on for Irrlicht 3D Engine by Doxygen 1.15.0