The mouse press is also handled in the Press
method. In general, Press
method receives key press, or a mouse press, or a mouse wheel use (see the documentation of TInputPressRelease
).
Everywhere in the engine, the mouse events also work on touch devices, when they correspond to the movement / touches of the fingers. When you use a touch device, then we only report left mouse button clicks (TInputPressRelease.MouseButton
will be buttonLeft
). When you use use the actual mouse on the desktop, then we only report touches by the 1st finger (TInputPressRelease.FingerIndex
will be 0
). The example code below checks for if Event.IsMouseButton(buttonLeft) then
and thus it will work on both desktop (detecting mouse click) and mobile (detecting touch).
Extend the TViewMain.Press
method implementation into this:
function TViewMain.Press(const Event: TInputPressRelease): Boolean;
begin
Result := inherited;
if Result then Exit;
if Event.IsKey(keySpace) then
begin
ImagePlayer.Color := Vector4(Random, Random, Random, 1);
Exit(true);
end;
if Event.IsMouseButton(buttonLeft) then
begin
ImagePlayer.Translation := ImagePlayer.Parent.ContainerToLocalPosition(Event.Position);
Exit(true);
end;
end;
The Event.Position
contains the mouse/touch position. It is expressed in the container coordinates, which means it is not affected by UI scaling or the UI hierarchy and anchors. It’s easiest to convert it to a position relative to some UI control using the TCastleUserInterface.ContainerToLocalPosition
method. In this case, we use ImagePlayer.Parent.ContainerToLocalPosition
, to use the resulting position to set ImagePlayer.Translation
. The ImagePlayer.Parent
is just another way to access ImageBackground
in this case. We want to calculate new player position, in the coordinates of ImagePlayer
parent, because that’s what ImagePlayer.Translation
expects.