Godot: advanced swiping mechanics - input

I have a VboxContainer as a child of a ScrollContainer and some text and buttons in it – a long list I can scoll through by finger-swiping on a touchscreen.
The code (based on https://github.com/godotengine/godot/issues/21137#issuecomment-414959543):
extends ScrollContainer
var swiping = false
var swipe_start
var swipe_mouse_start
var swipe_mouse_times = []
var swipe_mouse_positions = []
signal finger_is_swiping
func _ready():
mouse_filter = Control.MOUSE_FILTER_IGNORE
func _input(ev):
if ev is InputEventMouseButton:
if ev.pressed:
swiping = true
swipe_start = Vector2(get_h_scroll(), get_v_scroll())
swipe_mouse_start = ev.position
swipe_mouse_times = [OS.get_ticks_msec()]
swipe_mouse_positions = [swipe_mouse_start]
else:
swipe_mouse_times.append(OS.get_ticks_msec())
swipe_mouse_positions.append(ev.position)
var source = Vector2(get_h_scroll(), get_v_scroll())
var idx = swipe_mouse_times.size() - 1
var now = OS.get_ticks_msec()
var cutoff = now - 100
for i in range(swipe_mouse_times.size() - 1, -1, -1):
if swipe_mouse_times[i] >= cutoff: idx = i
else: break
var flick_start = swipe_mouse_positions[idx]
var flick_dur = min(0.3, (ev.position - flick_start).length() / 1000)
if flick_dur > 0.0:
var tween = Tween.new()
add_child(tween)
var delta = ev.position - flick_start
var target = source - delta * flick_dur * 8.0
#tween.interpolate_method(self, 'set_h_scroll', source.x, target.x, flick_dur, Tween.TRANS_QUAD, Tween.EASE_OUT)
tween.interpolate_method(self, 'set_v_scroll', source.y, target.y, flick_dur, Tween.TRANS_QUAD, Tween.EASE_OUT)
tween.interpolate_callback(tween, flick_dur, 'queue_free')
tween.start()
swiping = false
elif swiping and ev is InputEventMouseMotion:
var delta = ev.position - swipe_mouse_start
set_h_scroll(swipe_start.x - delta.x)
set_v_scroll(swipe_start.y - delta.y)
swipe_mouse_times.append(OS.get_ticks_msec())
swipe_mouse_positions.append(ev.position)
emit_signal("finger_is_swiping")
print ("finger is swiping")
It works quite nicely, but there are three hurdles I need help with:
While swiping, the print "finger is swiping" is being printed all the time, many times, and I therefore assume that the signal "finger_is_swiping" is being emitted as often as well. How can I have the signal being emitted only once per swipe? (Or is that a problem at all?)
How can I set a signal when my finger stops swiping (so when it's lifted from the touchscreen)?
I'd like the swipe-movement not to cause scrolling at all when touching a button in the list first. (My buttons work in a way so I can hold them down and make them not trigger by dragging the finger off... in such a case I'd like the list not to scroll despite the dragging.) I'd assume that I could have the button emit a signal which causes some "ignore swipe" or set the swipe speed to 0 maybe?
EDIT:
Yes, a simple swiping = false does this trick!

Related

I am trying to set all rigidbodys' velocity to 0, then to what it was before

So I have been trying to create a pause menu for the past few hours. However, I cannot figure out how to stop the rigidbodies from moving. If there is a way to stop all rigidbodies at once, please tell me, if not, I can set it to each and every script with a rigid body. Here is my code so far:
extends Position3D
onready var charCamera = get_viewport().get_camera()
##var direction = Camera.global_transform.basis.get_euler()
signal spawned(spawn)
export(PackedScene) var spawnling_scene
var linear_velocity_on_pause = 0
var not_paused_anymore = false
var paused = false
#var Popup1 = self.get_parent().get_parent().get_parent().get_node("Popup")
func _physics_process(_delta):
if self.get_parent().get_parent().get_parent().get_node("Popup").visible == false:
if Input.is_action_pressed("leftClick"):
spawn()
if paused == true:
not_paused_anymore = true
paused = false
if self.get_parent().get_parent().get_parent().get_node("Popup").visible == true:
linear_velocity_on_pause = spawnling_scene.instance().linear_velocity
paused = true
spawnling_scene.instance().set_mode(1)
spawnling_scene.instance().linear_velocity = get_parent().get_parent().get_parent().get_node("LinearVelocityOf0").linear_velocity
if not_paused_anymore == true:
spawnling_scene.instance().set_mode(0)
spawnling_scene.instance().linear_velocity = linear_velocity_on_pause
not_paused_anymore = false
func spawn():
var spawnling = spawnling_scene.instance()
spawnling.linear_velocity = charCamera.global_transform.basis.z * -100
#spawnling.global_transform.basis = charCamera.global_transform.basis
add_child(spawnling)
spawnling.set_as_toplevel(true)
emit_signal("spawned", spawnling)
##insert pause system
return spawnling
##var spawnling = spawnling_scene.instance()
##
## add_child(spawnling)
## spawnling.set_as_toplevel(true)
I'm not answering the question of how to set the velocity of all rigid bodies to zero.
If you want to make a pause menu, this is what you should know:
Godot has a puse system, which you can use like this to pause:
get_tree().paused = true
And to resume:
get_tree().paused = false
See Pausing Games.
Which Nodes gets to execute when get_tree().paused is set to true depend on their pause_mode property. By default they will all stop, but if you set their pause_mode to PAUSE_MODE_PROCESS they will continue to work when get_tree().paused is set to true. And that is what you want to do with the Node that make up your pause menu UI.
However, that system will not pause shaders. Their TIME will continue to tick. If you want to "freeze" shaders you can set a 0 to their time scaling like this:
VisualServer.set_shader_time_scale(0)
Set it to 1 for normal speed:
VisualServer.set_shader_time_scale(0)
And you can set other values to have them slow down or speed up.
Speaking of slow down and speed up. If you want to do that for the rest of the game (not just shaders), you can use Engine.time_scale. And if there is some timing that you don't want to be affected, you would have to write it using the time functions in the OS class.

How do you get motion blur working in SceneKit?

According to WWDC 2017, motionBlurIntensity was added as a property to SCNCamera. I've tried the following and failed to get SceneKit to blur my scene when the camera is moved:
Set wantsHDR to true
Add SCNDisableWideGamut as a Boolean with the value of YES in every Info.plist in my Xcode project
Move a SCNBox by changing its SCNNode's position in front of the camera with motionBlurIntensity set to 1.0
Move the camera itself by changing its SCNNode's position with motionBlurIntensity set to 1.0
Animate the camera using an SCNTransaction with motionBlurIntensity set to 1.0 instead of changing its position each frame
Do the above with motionBlurIntensity set to 500 or greater
I run the following code every rendered frame like so:
camNode.position = SCNVector3Make(cx, cy, cz);
camNode.eulerAngles = SCNVector3Make(rotx, roty, rotz);
camNode.camera.wantsDepthOfField = enableDOF;
camNode.camera.wantsHDR = enableHDR;
camNode.camera.zNear = camNearVal;
camNode.camera.zFar = camFarVal;
camNode.camera.focalLength = camFocalLength;
camNode.camera.usesOrthographicProjection = usingOrthoProjection;
if(!usingOrthoProjection)
{
camNode.camera.projectionTransform = SCNMatrix4FromGLKMatrix4(GLKMatrix4MakeWithArray(projection));
}
else
{
// Ortho options
camNode.camera.orthographicScale = orthoScale;
if(cam_projectionDir == 1)
camNode.camera.projectionDirection = SCNCameraProjectionDirectionHorizontal;
else
camNode.camera.projectionDirection = SCNCameraProjectionDirectionVertical;
}
// DOF
camNode.camera.sensorHeight = dof_sensorHeight;
camNode.camera.focusDistance = dof_focusDistance;
camNode.camera.fStop = dof_fStop;
camNode.camera.apertureBladeCount = dof_apertureBladeCount;
camNode.camera.focalBlurSampleCount = dof_focalBlurSampleCount;
// Motion blur
camNode.camera.motionBlurIntensity = motionBlurIntensity;
And here is where the SCNRenderer sets its pointOfView to the camera:
mainRenderer.scene = mainScene;
mainRenderer.pointOfView = camNode;
id<MTLCommandBuffer> myCommandBuffer = [_commandQueue commandBuffer];
[mainRenderer updateAtTime: currentFrame];
[mainRenderer renderWithViewport:CGRectMake(0,0,(CGFloat)_viewWidth, (CGFloat)_viewHeight) commandBuffer:myCommandBuffer passDescriptor:_renderPassDescriptor];
[myCommandBuffer commit];
HDR effects like Bloom and SSAO work properly, just not motion blur.
I'm using Xcode Version 10.1 on macOS Mojave.
I ran the Badger sample app and the motion blur in that project works on my computer.
Am I missing something here? Any insight would be greatly appreciated.
The default value of a motionBlurIntensity property is 0.0. It results in no motion blur effect. Higher values (toward a maximum of 1.0) create more pronounced motion blur effects. Motion blur is not supported when wide-gamut color rendering is enabled. Wide-gamut rendering is enabled by default on supported devices; to opt out, set the SCNDisableWideGamut key in your app's Info.plist file.
Test it with my code:
let cameraNode1 = SCNNode()
cameraNode1.camera = SCNCamera()
cameraNode1.camera?.motionBlurIntensity = 3 // MOTION BLUR
scene.rootNode.addChildNode(cameraNode1)
let move = CABasicAnimation(keyPath: "translation")
move.fromValue = NSValue(scnVector3: SCNVector3(x: 7, y: -5, z: 0))
move.toValue = NSValue(scnVector3: SCNVector3(x: 7, y: 5, z: 0))
move.duration = 0.5
move.repeatCount = 20
move.autoreverses = true
move.repeatCount = .infinity
let sphereNode1 = SCNNode()
sphereNode1.geometry = SCNSphere(radius: 2)
sphereNode1.addAnimation(move, forKey: "back and forth")
scene.rootNode.addChildNode(sphereNode1)
Works perfectly.

macOS Sierra: Emulate Mouse Down and Up

after an update to Sierra I had to find that Karabiner is not working anymore, which could emulate pointer clicks really well.
Any chance to get that via Swift or Apple Script or Obj.C ?
Background: Using Karabiner(and seil) I could bind caps-lock + d down and up to mouse down and up and in between the trackpad movement was understood. My trackpad is not processing keypress anymore but works still fine for pointer moves.
Answering myself, hacked it in hammerspoon. Was quite tricky to get chrome select working, maybe it saves somebody an hour or two:
1 ~/.hammerspoon $ cat init.lua
--[[ Left Keyboard Mouse (alt-d)
The main problem was to get chrome based apps select text when we drag via
keyboard.
You MUST return true always in the handle_drag otherwise it fails to select.
FF works, terminal works, chrome apps (atom, ...) don't.
But true is preventing further processing of the drag coords,
hs.mouse.getAbsolutePosition remains constant while dragging (!)
=> i.e. we MUST calc them via DeltaX, DeltaY, see below.
--]]
hs.alert.show("Config loaded")
-- all mechanics stolen from here:
-- local vimouse = require('vimouse')
-- vimouse('cmd', 'm')
now = hs.timer.secondsSinceEpoch
evt = hs.eventtap
evte = evt.event
evtypes = evte.types
evp=evte.properties
drag_last = now(); drag_intv = 0.01 -- we only synth drags from time to time
mp = {['x']=0, ['y']=0} -- mouse point. coords and last posted event
l = hs.logger.new('keybmouse', 'debug')
dmp = hs.inspect
-- The event tap. Started with the keyboard click:
handled = {evtypes.mouseMoved, evtypes.keyUp }
handle_drag = evt.new(handled, function(e)
if e:getType() == evtypes.keyUp then
handle_drag:stop()
post_evt(2)
return nil -- otherwise the up seems not processed by the OS
end
mp['x'] = mp['x'] + e:getProperty(evp.mouseEventDeltaX)
mp['y'] = mp['y'] + e:getProperty(evp.mouseEventDeltaY)
-- giving the key up a chance:
if now() - drag_last > drag_intv then
-- l.d('pos', mp.x, 'dx', dx)
post_evt(6) -- that sometimes makes dx negative in the log above
drag_last = now()
end
return true -- important
end)
function post_evt(mode)
-- 1: down, 2: up, 6: drag
if mode == 1 or mode == 2 then
local p = hs.mouse.getAbsolutePosition()
mp['x'] = p.x
mp['y'] = p.y
end
local e = evte.newMouseEvent(mode, mp)
if mode == 6 then cs = 0 else cs=1 end
e:setProperty(evte.properties.mouseEventClickState, cs)
e:post()
end
hs.hotkey.bind({"alt"}, "d",
function(event)
post_evt(1)
handle_drag:start()
end
)
and alt I mapped to capslock via karabiner elements.

three.js Unproject camera within group

I have a camera as child within a Group object and I need to get the origin/direction:
var cameraRig = new THREE.Group();
cameraRig.add( cameraPerspective );
cameraRig.add( cameraOrtho );
scene.add( cameraRig );
function relativeMousePosition () {
var canvasBoundingBox = renderer.domElement.getBoundingClientRect();
var mouse3D = new THREE.Vector3(0, 0, 0.5);
mouse3D.x = ((mouseX - 0) / canvasBoundingBox.width) * 2 - 1;
mouse3D.y = -((mouseY - 0) / canvasBoundingBox.height) * 2 + 1;
return mouse3D;
}
cameraRig.position.set(89,34,91);
cameraRig.lookAt(something.position);
cameraPerspective.position.set(123,345,123);
var dir = relativeMousePosition().unproject(camera).sub(cameraPerspective.position).normalize();
var origin = cameraPerspective.position;
The above code gives a origin + direction with the context of the cameraRig. When I exclude the camera out, having the scene as direct parent, it gives me the world origin/direction which I want. So how to incorporate the cameraRig to get world origin/direction, so I can do picking or whatever?
FIDDLE: https://jsfiddle.net/647qzhab/1/
UPDATE:
As mentioned in the comment by Falk:
var dir = relativeMousePosition().unproject(camera).sub(cameraPerspective.getWorldPosition()).normalize();
var origin = cameraPerspective.getWorldPosition();
The result is better, but not yet fully satisfiing, as the camera rotation seems not applied yet.
I need to update matrixWorld for the cameraRig:
cameraRig.position.set(89,34,91);
cameraRig.lookAt(something.position);
cameraPerspective.position.set(123,345,123);
cameraRig.updateMatrixWorld(true);
cameraPerspective.updateMatrixWorld(true);

Flex 3 - Enable context menu for text object under a transparent PNG

Here is the situation. In my app I have an overlay layer that is composed of a transparent PNG. I have replaced the hitarea for the png with a 1x1 image using the following code:
[Bindable]
[Embed(source = "/assets/1x1image.png")]
private var onexonebitmapClass:Class;
private function loadCompleteHandler(event:Event):void
{
// Create the bitmap
var onexonebitmap:BitmapData = new onexonebitmapClass().bitmapData;
var bitmap:Bitmap;
bitmap = event.target.content as Bitmap;
bitmap.smoothing = true;
var _hitarea:Sprite = createHitArea(onexonebitmap, 1);
var rect:flash.geom.Rectangle = _box.toFlexRectangle(sprite.width, sprite.height);
var drawnBox:Sprite = new FlexSprite();
bitmap.width = rect.width;
bitmap.height = rect.height;
bitmap.x = -loader.width / 2;
bitmap.y = -loader.height / 2;
bitmap.alpha = _alpha;
_hitarea.alpha = 0;
drawnBox.x = rect.x + rect.width / 2;
drawnBox.y = rect.y + rect.height / 2;
// Add the bitmap as a child to the drawnBox
drawnBox.addChild(bitmap);
// Rotate the object.
drawnBox.rotation = _rotation;
// Add the drawnBox to the sprite
sprite.addChild(drawnBox);
// Set the hitarea to drawnBox
drawnBox.hitArea = _hitarea;
}
private function createHitArea(bitmapData:BitmapData, grainSize:uint = 1):Sprite
{
var _hitarea:Sprite = new Sprite();
_hitarea.graphics.beginFill(0x900000, 1.0);
for (var x:uint = 0; x < bitmapData.width; x += grainSize)
{
for (var y:uint = grainSize; y < bitmapData.height; y += grainSize)
{
if (x <= bitmapData.width && y <= bitmapData.height && bitmapData.getPixel(x, y) != 0)
{
_hitarea.graphics.drawRect(x, y, grainSize, grainSize);
}
}
}
_hitarea.graphics.endFill();
return _hitarea;
}
This is based off the work done here: Creating a hitarea for PNG Image with transparent (alpha) regions in Flex
Using the above code I am able to basically ignore the overlay layer for all mouse events (click, double click, move, etc.) However, I am unable to capture the right click (context menu) event for items that are beneath the overlay.
For instance I have a spell check component that checks the spelling on any textitem and like most other spell checkers if the word is incorrect or not in the dictionary underlines the word in red and if you right click on it would give you a list of suggestions in the contextmenu. This is working great when the text box is not under the overlay, but if the text box is under the overlay I get nothing back.
If anyone can give me some pointers on how to capture the right click event on a textItem that is under a transparent png that would be great.