Converting mouse position functionality to work with touchscreen - c#

I'm developing in Unity, C#, and I have a bit of code that checks for player activity based on mouse position and it's working well but I'm needing to also check player activity on a touchscreen (not a mobile phone touchscreen, but a touchscreen attached to a pc). How should I modify the code that I have below to also work with touch?
private void Start()
{
InvokeRepeating("LastMousePosition", 0, _checkMousePositionTimingInterval);
}
private void Update()
{
_currentMousePosition = Input.mousePosition;
}
void LastMousePosition()
{
_prevMousePosition = Input.mousePosition;
}
void CheckPlayerIdle()
{
if (_currentMousePosition != _prevMousePosition)
UserActive = true;
else if (_currentMousePosition == _prevMousePosition)
UserActive = false;
}

Well for touch you start your inactivity timer if you don't get any touch inputs and wait for x duration.
for eg:
private void Update()
{
if(Input.touchCount == 0)
{
if(!checkingForInactivity)
{
checkingForInactivity = true;
myRoutine = StartCoroutine(CheckForInactivity());
}
}
else
{
if(checkingForInactivity) StopCoroutine(myRoutine);
}
}
Ienumrable CheckForInactivity()
{
yield new waitForSecond(3.0f);
//user is inactive
}
}

Related

Need a boolean check every frame(update call).But the function called from that boolean check should be called only once

So i am working on a project using a webcam.If i go out-of-screen(view of the camera) a timer starts which track the time i am out of view and if it goes above a certain max value my game gets paused.
Similarly for the In-screen view(inside camera view), timer starts and after max value it resumes the game.
void Update()
{
if (InFrontOfScreen()) //This is a condition
{
isInFront = true;
}
else
{
isInFront = false;
}
InView();
Pausing();
}
private void Pausing()
{
if (isPaused)
Time.timeScale = 0f;
else
Time.timeScale = 1f;
}
private void InView()
{
if (isInFront)
{
inViewTime += Time.unscaledDeltaTime;
if (inViewTime >= maxInViewTime)
{
isPaused = false;
}
outOfViewTime = 0f;
}
else
{
outOfViewTime += Time.unscaledDeltaTime;
if (outOfViewTime >= maxOutOfViewTime)
{
isPaused = true;
}
inViewTime = 0f;
}
}
Now in another script I have to call functions that depend on whether the game is paused or not.
void Update()
{
SwitchCameras();
}
private void SwitchCameras()
{
if(PauseController.isPaused)
{
gameCam.enabled = false;
mainCam.cullingMask = pausedLayerMask;
}
else
{
gameCam.enabled = true;
mainCam.cullingMask = originalLayerMask;
}
}
The problem is that this gameCam.enabled and mainCam should be called only once when the bool isPaused changes.It is being called every frame. I get the answer right but I want it to be called only once and not every frame.Is there a way to acheive this?
Though isPaused can change back and forth the functions should be called once and then again when isPaused changes .
Thank you
From what I can see you only need to cache the value and when a new update is called just check if the value changed
// Somewhere have a field that saves previous state
private bool _wasPaused;
void Update()
{
SwitchCameras();
}
private void SwitchCameras()
{
if (_wasPaused != PauseController.isPaused)
{
if (PauseController.isPaused)
{
gameCam.enabled = false;
mainCam.cullingMask = pausedLayerMask;
}
else
{
gameCam.enabled = true;
mainCam.cullingMask = originalLayerMask;
}
}
_wasPaused = PauseController.isPaused;
}
We can use a private variable and a property. This way we can check to see when a property changes value, and just process an action when the value changes.
Very quickly, this should be a way to achieve what you’re trying to do:
private bool _isInFront;
public bool isInFront
{
get => _isInFront;
set
{
if ( _isInFront == value )
return;
_isInFront = value;
InView();
}
}
private void Update ()
{
isInFront = InFrontOfScreen(); //This is a condition
Pausing();
}
The problem is that this gameCam.enabled and mainCam should be called only once when the bool isPaused changes
Well in that case (and in general) you should not poll check flags in Update at all but rather make your code reactive event driven and only react a single time the moment the value actually is changed.
So in your first script I would add a
public event Action<bool> pauseStateChanged;
whenever you set the state of isPaused also invoke the event accordingly and do the change check already here in the responsible class instead of all listeners having to track it themselves
...
// Check makes sure the event is really only called when the state is changed
if(!isPaused)
{
isPaused = true;
pauseStateChanged?.Invoke(true);
}
and then in the other script(s) attach a listener once which will only be invoked when the event is invoked -> when the state actually changed
private void Start()
{
// start listening to the event
PauseController.pauseStateChanged += SwitchCameras;
// initially call the callback once with the current state
SwitchCameras(PauseController.isPaused);
}
private void OnDestroy()
{
// remove the listener once not needed anymore to avoid exceptions
PauseController.pauseStateChanged -= SwitchCameras;
}
private void SwitchCameras(bool isPaused)
{
gameCam.enabled = !isPaused;
// Using a ternary here makes this way easier to read imho
mainCam.cullingMask = isPaused ? pausedLayerMask : originalLayerMask;
}
And following this very same principle you could also make the rest of your first script reactive the same way instead of calling things every frame in Update I would probably use a Coroutine and do
private Coroutine routine;
void Update()
{
var currentIsInFront = InFrontOfScreen();
// Did state change?
if(isInFront != currentIsInFront)
{
if(routine != null)
{
StopCoroutine(routine);
}
isInFront = currentIsInFront;
routine = StartCoroutine(PauseRoutine);
}
}
private IEnumerator PauseRoutine()
{
var newPausedState = !isInFront;
if(isPaused != newPausedState)
{
var delay = isInFront ? maxInViewTime : maxOutOfViewTime;
yield return new WaitForSecondsRealtime(delay);
isPaused = newPausedState;
pauseStateChanged?.Invoke(newPausedState);
Time.timeScale = newPausedState ? 0f : 1f;
}
}

unity Photon OnTriggerStay2D only works for host

im adding perks (upgrades) to my game but they only work properly when you play alone, when multiple people are in the game, the functionality stops working.
when the player 1 (host) enters the trigger, a pop up message appears saying Press F to purchase etc etc.. but when player 2 enters the trigger, the message does not appear on his screen but on player 1's screen.
script:
public void Update()
{
if(!view.IsMine) return;
if(Input.GetKey(KeyCode.F))
{
isPressingF = true;
}
else
{
isPressingF = false;
}
}
void OnTriggerStay2D (Collider2D collider)
{
if(!view.IsMine) return;
if (!ownedHalet)
{
if(collider.gameObject.CompareTag("Player"))
{
juggConfirm.SetActive(true);
if (isPressingF)
{
if(PointSystem.Instance.points < 2500 )
return;
BuyPerkHalet();
}
}
}
}
```

Detect one tap and long tap on touch

I am trying to implement two touch functions. One tap and long tap. I have implemented one tap which is pretty straightforward but for a long tap function, a timer must be set?
I would like the long press to be active only after 1 second of holding the tap and then the timer should get reset on release. How do I do this?
public float longTapTime;
void Update()
{
if ((Input.touchCount > 0) && (Input.GetTouch (0).phase == TouchPhase.Began)) {
//One tap
}
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
longTapTime = 0;
}
}
using UnityEngine;
public class example : MonoBehaviour
{
[SerializeField]
private float long_tap_consider_duration = 1.0f;
private float time_helper;
private float duration;
private bool is_touched;
private void Start()
{
time_helper = 0;
duration = 0;
is_touched = false;
}
private void Update()
{
if (Input.touchCount > 0)
ProcessInput();
}
private void ProcessInput()
{
if (is_touched && ((Input.GetTouch(0).phase == TouchPhase.Ended) || (Input.GetTouch(0).phase == TouchPhase.Canceled)))
{
if (duration > long_tap_consider_duration)
OnLongTap();
else OnTap();
}
if (!is_touched && (Input.GetTouch(0).phase == TouchPhase.Began))
{
time_helper = Time.time;
is_touched = true;
}
duration = Time.time - time_helper;
}
//Callback function, when just a short tap occurs
private void OnTap()
{
Debug.Log("Short Tap");
}
//Callback function, when long tap occurs
private void OnLongTap()
{
Debug.Log("Long Tap");
}
}
actually, if you are using the new input system, this is a built in feature and does not need any code.
find your Input Actions ".inputActions"
find the button on the list of inputs registered
with that item selected, find the plus "+" next to the word interactions on the right hand side
add a "hold" interaction from the list and set desired hold time.
for more information on the input action asset system: https://www.youtube.com/watch?v=mvuXOyKz7k4

The object of type 'GameObject' has been destroyed but you are still trying to access it

So I am working on a runner game and it is almost done. The problem is that I am testing the Pause Panel and when player touches a zombie, pause panel shows up and I am restarting the game again by pressing the restart button. But when I touch the zombie again panel doesnt show up and gives me the error in the title. I am stuck and any help will be appreciated. This is the code and I referenced to the line that error sends me :
[SerializeField]
private GameObject pausePanel;
[SerializeField]
private Button RestartGameButton;
[SerializeField]
private Text ScoreText;
private int score;
void Start ()
{
pausePanel.SetActive(false);
ScoreText.text = score + "M";
StartCoroutine(CountScore());
}
IEnumerator CountScore()
{
yield return new WaitForSeconds(0.6f);
score++;
ScoreText.text = score + "M";
StartCoroutine(CountScore());
}
void OnEnable()
{
PlayerDeath.endgame += PlayerDiedEndTheGame;
}
void OnDisable()
{
PlayerDeath.endgame += PlayerDiedEndTheGame;
}
void PlayerDiedEndTheGame()
{
if (!PlayerPrefs.HasKey("Score"))
{
PlayerPrefs.SetInt("Score", 0);
}
else
{
int highscore = PlayerPrefs.GetInt("Score");
if(highscore < score)
{
PlayerPrefs.SetInt("Score", score);
}
}
pausePanel.SetActive(true); //this is the line that error sends me but I cant figure it out because I didnt try to destroy the panel in the first place.
RestartGameButton.onClick.RemoveAllListeners();
RestartGameButton.onClick.AddListener(() => RestartGame());
Time.timeScale = 0f;
}
public void PauseButton()
{
Time.timeScale = 0f;
pausePanel.SetActive(true);
RestartGameButton.onClick.RemoveAllListeners();
RestartGameButton.onClick.AddListener(() => ResumeGame());
}
public void GoToMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("MainMenu");
}
public void ResumeGame()
{
Time.timeScale = 1f;
pausePanel.SetActive(false);
}
public void RestartGame()
{
Time.timeScale = 1f;
SceneManager.LoadScene("Gameplay");
}
I found the solution. It was a simple mistake on the OnDisable method. I deleted the += sign and changed it with -= sign because it was enabling the event when it was supposed to disable.

Cancelling audio clip before starting a new one?

I almost have a working radio, where the player can walk up to it, press a button and cycle through songs. Everything works except for that with each button press the new song will play but the original will continue to play underneath it. For each new song that is played a new object is created but they are all called 'One Shot Audio,' so I don't know how to destroy them. If I can fix this bug then this should be a useful radio script for anyone who wants to use it.
Update, here is my modified radio code, now working, with the help of the answer below:
void OnTriggerEnter2D(Collider2D target) {
if (target.gameObject.tag == "radio") {
radioEnter = true;
}
}
void OnTriggerExit2D(Collider2D target) {
if (target.gameObject.tag == "radio") {
radioEnter = false;
}
}
public void radioUse(){
if ((Input.GetKeyDown (KeyCode.M)) && song3on == true && radioEnter == true) {
TurnOn ();
song1on = true;
song2on = false;
song3on = false;
}
else if ((Input.GetKeyDown (KeyCode.M)) && song1on == true && radioEnter == true) {
TurnOff ();
song1on = false;
song2on = true;
song3on = false;
TurnOn();
}
else if ((Input.GetKeyDown (KeyCode.M)) && song2on == true && radioEnter == true) {
TurnOff ();
song1on = false;
song2on = false;
song3on = true;
TurnOn ();
}
}
public void Update() {
raidoUse();
}
Since PlayClipAtPoint does not return an AudioSource to manage you should not use it for these kind of sounds. I recommend setting up your radio with one AudioSource and multiple AudioClips in a array. Just drag the clips you want to the inspector and use the public methods to control the radio. This way you can reuse it with different songs.
The following code is not tested.
Public class Radio : MonoBehaviour
{
AudioSource output;
public AudioClip[] songs;
int songIndex = 0;
void Start(){
output = gameObject.AddComponent<AudioSource>();
}
public void ToggleSong(){
songIndex++;
output.clip = songs[songIndex % songs.Length];
output.Play();
}
public void TurnOn(){
ToggleSong();
}
public void TurnOff(){
output.Stop();
}

Categories