I want to determine whether the camera changed event was initiated from the user or not. (i have to make different actions based on that). So if the user pans a camera with the finger, i have to close sg, but if i moved the camera with the API, i do not.
Currently i cannot decide it was a user event or not, in my OnCameraChangeListener, because the onCameraChange(CameraPosition var1) method does not provide any kind of information about that.
I also tried to save the last marker position which i animated onto programmatically, and check that in the listener method:
map.setOnCameraChangeListener(new GoogelMap.onCameraChangeListener {
public void onCameraChange(CameraPosition position) {
if (!cameraPosition.target.equals(lastClickedMarker)) {
// this is a user event
}
}
I set the lastClickedMarker with the OnMarkerClickListener. I found out i cannot rely on this, because the cameraPosition and lastClickedMarker coordinates will always differ a little, even if really animate to that marker programmatically with animateCamera().
Is there any way to solve this?
You can set a boolean before you change the camera programatically, and check if it is set (and unset) in the onCameraChange method.
Something like this:
// Moving programmatically
cameraMovedProgrammatically = true;
map.animateCamera(cameraUpdate);
And checking it:
public void onCameraChange(CameraPosition position) {
if (cameraMovedProgrammatically) {
// this is not a user event
cameraMovedProgrammatically = false;
} else {
// this is a user event
}
}
Related
Even the official documentation has borderline insane recommendations to solve what is probably one of the most common UI/3D interaction issues:
If I click while the cursor is over a UI button, both the button (via the graphics raycaster) and the 3D world (via the physics raycaster) will receive the event.
The official manual:
https://docs.unity3d.com/Packages/com.unity.inputsystem#1.2/manual/UISupport.html#handling-ambiguities-for-pointer-type-input essentially says "how about you design your game so you don't need 3D and UI at the same time?".
I cannot believe this is not a solved problem. But everything I've tried failed. EventSystem.current.currentSelectedGameObject is sticky, not hover. PointerData is protected and thus not accessible (and one guy offered a workaround via deriving your own class from Standalone Input Module to get around that, but that workaround apparently doesn't work anymore). The old IsPointerOverGameObject throws a warning if you query it in the callback and is always true if you query it in Update().
That's all just mental. Please someone tell me there's a simple, obvious solution to this common, trivial problem that I'm just missing. The graphics raycaster certainly stores somewhere if it's over a UI element, right? Please?
I've looked into this a fair bit and in the end, the easiest solution seems to be to do what the manual says and put it in the Update function.
bool pointerOverUI = false;
void Update()
{
pointerOverUI = EventSystem.current.IsPointerOverGameObject();
}
Your frustration is well founded: there are NO examples of making UI work with NewInput which I've found. I can share a more robust version of the Raycaster workaround, from Youtube:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;
/* Danndx 2021 (youtube.com/danndx)
From video: youtu.be/7h1cnGggY2M
thanks - delete me! :) */
public class SCR_UiInteraction : MonoBehaviour
{
public GameObject ui_canvas;
GraphicRaycaster ui_raycaster;
PointerEventData click_data;
List<RaycastResult> click_results;
void Start()
{
ui_raycaster = ui_canvas.GetComponent<GraphicRaycaster>();
click_data = new PointerEventData(EventSystem.current);
click_results = new List<RaycastResult>();
}
void Update()
{
// use isPressed if you wish to ray cast every frame:
//if(Mouse.current.leftButton.isPressed)
// use wasReleasedThisFrame if you wish to ray cast just once per click:
if(Mouse.current.leftButton.wasReleasedThisFrame)
{
GetUiElementsClicked();
}
}
void GetUiElementsClicked()
{
/** Get all the UI elements clicked, using the current mouse position and raycasting. **/
click_data.position = Mouse.current.position.ReadValue();
click_results.Clear();
ui_raycaster.Raycast(click_data, click_results);
foreach(RaycastResult result in click_results)
{
GameObject ui_element = result.gameObject;
Debug.Log(ui_element.name);
}
}
}
So, just drop into my "Menusscript.cs"?
But as a pattern, this is terrible for separating UI concerns. I'm currently rewiring EVERY separately-concerned PointerEventData click I had already working, and my question is, Why? I can't even find how it's supposed to work: to your point there IS no official guide at all around clicking UI, and it does NOT just drop-on-top.
Anyway, I haven't found anything yet which makes new input work easily on UI, and definitely not found how I'm going to sensibly separate Menuclicks from Activityclicks while keeping game & ui assemblies separate.
Good luck to us all.
Unity documentation for this issue with regard to Unity.InputSystem can be found at https://docs.unity3d.com/Packages/com.unity.inputsystem#1.3/manual/UISupport.html#handling-ambiguities-for-pointer-type-input.
IsPointerOverGameObject() can always return true if the extent of your canvas covers the camera's entire field of view.
For clarity, here is the solution which I found worked best (accumulated from several other posts across the web).
Attach this script to your UI Canvas object:
public class CanvasHitDetector : MonoBehaviour {
private GraphicRaycaster _graphicRaycaster;
private void Start()
{
// This instance is needed to compare between UI interactions and
// game interactions with the mouse.
_graphicRaycaster = GetComponent<GraphicRaycaster>();
}
public bool IsPointerOverUI()
{
// Obtain the current mouse position.
var mousePosition = Mouse.current.position.ReadValue();
// Create a pointer event data structure with the current mouse position.
var pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = mousePosition;
// Use the GraphicRaycaster instance to determine how many UI items
// the pointer event hits. If this value is greater-than zero, skip
// further processing.
var results = new List<RaycastResult>();
_graphicRaycaster.Raycast(pointerEventData, results);
return results.Count > 0;
}
}
In class containing the method which is handling the mouse clicks, obtain the reference to the Canvas UI either using GameObject.Find() or a public exposed variable, and call IsPointerOverUI() to filter clicks when over UI.
Reply to #Milad Qasemi's answer
From the docs you have attached in your answer, I have tried the following to check if the user clicked on a UI element or not.
// gets called in the Update method
if(Input.GetMouseButton(0) {
int layerMask = 1 << 5;
// raycast in the UI layer
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, layerMask);
// if the ray hit any UI element, return
// don't handle player movement
if (hit.collider) { return; }
Debug.Log("Touched not on UI");
playerController.HandlePlayerMovement(x);
}
The raycast doesn't seem to detect collisions on UI elements. Below is a picture of the Graphics Raycaster component of the Canvas:
Reply to #Lowelltech
Your solution worked for me except that instead of Mouse I used Touchscreen
// Obtain the current touch position.
var pointerPosition = Touchscreen.current.position.ReadValue();
An InputSytem is a way to receive new inputs provided by Unity. You can't use existing scripts there, and you'll run into problems like the original questioner. Answers with code like "if(Input.GetMouseButton(0)" are invalid because they use the old system.
I am struggling to find a good tutorial or informations that would allow me to select multiple objects in 3D in a user friendly manner.
So far, the best tutorial I found is this one : https://sharpcoderblog.com/blog/unity-3d-rts-style-unit-selection. The tutorial works by using the transform.position of the selectable objects and checking if it within the user's selection.
What I wish is to have the user be able to select a unit even if it is only partially within the user's selection such as most RTS games do ( both in 2D and 3D ).
One possibility would be to create a temporary mesh using the camera's clipping distances and the user's selection and then check for collisions but I was not able to find any tutorials using this method nor do I know if it is the best approach to the subject.
If I understand correctly you want to
somehow start a selection
collect every object that was "hit" during the collection
somehow end the collection
Couldn't you simply use raycasting? I will assume simple mouse input for now but you could basically port this to whatever input you have.
// Just a little helper class for an event in the Inspector you can add listeners to
[SerializeField]
public class SelectionEvent : UnityEvent<HashSet<GameObject>> { }
public class SelectionController : MonoBehaviour
{
// Adjust via the Inspector and select layers that shall be selectable
[SerializeField] private LayerMask includeLayers;
// Add your custom callbacks here either via code or the Inspector
public SelectionEvent OnSelectionChanged;
// Collects the current selection
private HashSet<GameObject> selection = new HashSet<GameObject>();
// Stores the current Coroutine controlling he selection process
private Coroutine selectionRoutine;
// If possible already reference via the Inspector
[SerializeField] private Camera _mainCamera;
// Otherwise get it once on runtime
private void Awake ()
{
if(!_mainCamera) _mainCamera = Camera.main;
}
// Depending on how exactly you want to start and stop the selection
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
StartSelection();
}
if(Input.GetMouseButtonUp(0))
{
EndSelection();
}
}
public void StartSelection()
{
// if there is already a selection running you don't wanr to start another one
if(selectionRoutine != null) return;
selectionRoutine = StartCoroutine (SelectionRoutine ());
}
public void EndSelection()
{
// If there is no selection running then you can't end one
if(selectionRoutine == null) return;
StopCoroutine (selectionRoutine);
selectionRoutine = null;
// Inform all listeners about the new selection
OnSelectionChanged.Invoke(new HashSet<GameObject>(selection);
}
private IEnumerator SelectionRoutine()
{
// Start with an empty selection
selection.Clear();
// This is ok in a Coroutine as long as you yield somewhere within it
while(true)
{
// Get the ray shooting forward from the camera at the mouse position
// for other inputs simply replace this according to your needs
var ray = _mainCamera.ScreenPointToRay(Input.mousePosition);
// Check if you hit any object
if(Physics.Raycast(ray, out var hit, layerMask = includeLayers ))
{
// If so Add it once to your selection
if(!selection.Contains(hit.gameObject)) selection.Add(hit.gameObject);
}
// IMPORTANT: Tells Unity to "pause" here, render this frame
// and continue from here in the next frame
// (without this your app would freeze in an endless loop!)
yield return null;
}
}
}
Ofcourse you could do it directly in Update in this example but I wanted to provide it in a way where you can easily exchange the input method according to your needs ;)
From UX side you additionally might want to call a second event like OnSelectionPreviewUpdate or something like this every time you add a new object to the selection in order to be able to e.g. visualize the selection outcome.
I might have understood this wrong and it sounds like you rather wanted to get everything inside of a drawn shape.
This is slightly more complex but here would be my idea for that:
Have a dummy selection Rigidbody object that by default is disabled and does nothing
don't even have a renderer on it but a mesh filter and mesh collider
while you "draw" create a mesh based on the input
then use Rigidbody.SweepTestAll in order to check if you hit anything with it
Typed on smartphone but I hope the idea gets clear
I think I would try to create a PolygonCollider2D because it is quite simple comparing to creating a mesh. You can set its path (outline) by giving it 2D points like location of your pointer/mouse. Use the SetPath method for it. You can then use one of its methods to check if another point in space overlaps with that collider shape.
While the PolygonCollider2D interacts with 2D components you can still use its Collider2D.OverlapPoint method to check positions/bounds of your 3D objects after translating it to 2D space.
You can also use its CreateMesh method to create a mesh for drawing your selection area on the screen.
You can read more about the PolygonCollider2D here.
Hope it makes sens and hope it helps.
I'm wondering if I can get some help on understanding how to use the timeline
I plan to have the character walking along a path with triggers that will activate the timeline,
I have set up a simple state machine on the monkey
which would be triggered by the path to play the timeline, that part works fine and I can see the events firing
How could I play part of the timeline when triggered (is that even possible?)
where the entire sequence is held Walk>Jump>Walk>Look>Walk>Idle
Or what would I need to do to be able to achieve playback of a clip/or part of a sequence of clips
On the monkey:
public enum State
{
WalkHappy,
Look,
Jump,
}
IEnumerator WalkHappyState()
{
Debug.Log("WalkHappy: Enter");
**//walk sequence with timeline here??**
while (state == State.WalkHappy)
{
yield return 0;
}
Debug.Log("WalkHappy: Exit");
NextState();
}
Called on the paths event listener when triggered
private void OnCustomEvent(string eventname)
{
if (eventname.Contains("MonkeyRunningJumpUp"))
{
GameObject tempMonkey = GameObject.FindGameObjectWithTag("Player");
Monkey tempMonkeyState = tempMonkey.GetComponent<Monkey>();
tempMonkeyState.state = Monkey.State.Jump;
}
}
I have seen its possible to control where the playback starts on a timeline, but I don't know how to force a range/clip to play then pause at the end of the clip rather than the end of the entire sequence
THE question is.. how to stop/pause at end of a clip to resume later?
playableDirector = myPlayableDirectorGO.GetComponent<PlayableDirector>();
Debug.Log(timeLinePosition);
playableDirector.time = timeLinePosition / ((TimelineAsset)playableDirector.playableAsset).editorSettings.fps;
playableDirector.RebuildGraph();
playableDirector.Play();
with thanks Natalie :)
First of all, I recommend to install Default Playables if you haven’t done it yet.
Use Timeline Signals and markers to do something at the end of timeline or at certain point. Also, there is PlayableDirector.stopped event.
You can use pause and resume methods;
In the game menu i want the menu items slide away from the screen and then scene changes.
I can't seem to make it work one by one, they seems to execute the same time so there is no time for the menu items to move.
#Override
public void onBackKeyPressed()
{
// SceneManager.getInstance().loadMenuScene(engine);
if(hasChildScene()) {
/* Remove the menu and reset it. */
menuOut();
this.gameMenuChildScene.back();
} else {
/* Attach the menu. */
createGameMenuChildScene();
}
}
The AndEngine Cookbook designed an animated game menu by making it an Entity and attaching it to the HUD, no Scene changes at all.
Otherwise, why don't you make a Callback once the animation is complete to change the scene?
-Sorry i can't comment yet and i wanted to help
U can do it like this: where 2f is time in seconds. It's not nice but it should work.
this.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
resourcesManager.engine.unregisterUpdateHandler(pTimerHandler);
//change scene here
}
}));
You also have isFinished() method in your EntityModifier. You can initialize onUpdate and check isFinished() method. When it returns true you will change the scene. It more elastic and nicer way to do it. I can't verify it right now so you have to check the soultion yourself.
My app has a sliding drawer for notifications. I've managed to get it to function like the android notifications including the "clear all" button.
When the clear all button is clicked my database is cleared, my list adapter is refreshed, and my list adapter gets set to the list. The view updates and the list is cleared.
When I added slide-out animation (just like jelly bean) I got a NullPointerException. The issue crops up when my adapter is set. If I comment out setting the adapter the animation runs without a problem.
// Animation
int count = drawer_list.getCount();
for (int i = 0; i < count; i++) {
View view = drawer_list.getChildAt(i);
if (view != null) {
// create an Animation for each item
Animation animation = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
animation.setDuration(300);
// ensure animation final state is "persistent"
animation.setFillAfter(true);
// calculate offset (bottom ones first, like in notification panel)
animation.setStartOffset(300 * (count - 1 - i));
// animation listener to execute action code
if (i == 0) {
animation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
// NOT USED
}
public void onAnimationRepeat(Animation animation) {
// NOT USED
}
public void onAnimationEnd(Animation animation) {
// Clear table
notifications.flushNotificationTempTable_ActiveOnly();
// Update list adapter
refreshNotifications();
// Close drawer
notification_drawer.close();
}
});
}
view.startAnimation(animation);
}
}
The trouble spot is in the refreshNotifications() method when the line drawer_list.setAdapter(notificationAdapter); executes. I use this method and adapter all throughout my app and, as I said above, it works flawlessly without the animations.
I was able to solve this by eliminating the animation listener and adding a delayed runnable after it that ran my post animation code.
I was unable to find a way to set a new adapter (required because i used a custom adapter) inside the animation listener. If anyone knows how to do this I would like to know.