Тёмный

Unity - Multiple Touches on Mobile Device [Input.GetTouch] 

Press Start
Подписаться 24 тыс.
Просмотров 38 тыс.
50% 1

In this tutorial I explain how to store multiple touches within a custom list to then spawn objects that follow the movement of each touch.
SUBSCRIBE: bit.ly/2Js78lE
============
In this video, we cover:
+ 0:30 - Setting Up A Custom List Script
+ 1:25 - Creating a Script to Detect Multiple Touches
+ 2:20 - Creating a While Loop to cycle between touches
+ 2:55 - The three different touch phases we will be using
+ 3:30 - Detecting Touch Start, End and Move
+ 4:10 - Testing our touches on a mobile device
+ 4:50 - Creating a function to spawn our circle prefabs
+ 6:15 - Adding our touches to our list
+ 6:45 - Searching our list and removing our touch after it ends
+ 8:08 - Moving our circle when the touch is moved
COPY & PASTE CODE FROM THIS TUTORIAL:
pressstart.vip/tutorials/2018...
UNITY DEVELOPER REMOTE APP:
docs.unity3d.com/Manual/Unity...
RELATED VIDEOS REGARDING SCREEN SPACE CONVERSION:
Orthographic: • Pinch to Zoom and Pann...
Perspective: • Unity - Mobile Panning...
MORE TUTORIALS:
pressstart.vip/unity-tutorials

Опубликовано:

 

10 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 60   
@brandonhohn245
@brandonhohn245 5 лет назад
This channel is absolutely, crazily underrated. This man deserves so much more than he gets. The man has a website with an attractive interface for his videos for simplicity! And his tutorials skip all the bs! Thank you!
@pressstart6864
@pressstart6864 5 лет назад
And the best comment of the year goes to you, sir. Thank you for the kind words my friend.
@brandonhohn245
@brandonhohn245 5 лет назад
@@pressstart6864 Credit where credit is due! If I were you, I'd either do a small amount of advertising for your channel, or I'd try to collab with blackthorn prod or brackets. You offer something that not even the top channels have, you'd be an instant hit!
@pressstart6864
@pressstart6864 5 лет назад
@@brandonhohn245 we don't have any money to do advertising, so we rely soley on sharing, youtube alogrithms and search engine results. I've reached out to both Brackey's and BlackthornProd multiple times with no success. I'm too small right now, but the numbers multiply each month, so I'm just being patient. They'll notice me eventually.
@brandonhohn245
@brandonhohn245 5 лет назад
@@pressstart6864 I think it's crazy how well organized you are with the website, the graphics you use in the tutorials, and just general quality. Once you hit like the 20k mark, I guarantee you'll rise exponentially fast
@stefanstoicescu7165
@stefanstoicescu7165 4 года назад
After trying for 12 hours to make it my own way, and I almost made it :P... I came back to this tutorial, is much cleaner and it provides me with a position. Thank you very much for taking the time to post this. It got stuck when using "while", so I replaced it with a "for" instead. Not sure why, it happened to me before, maybe because of the version that I'm using, or maybe Unity isn't "while" friendly altogether. Cheers, thanks again.
@miceonvenus647
@miceonvenus647 Год назад
Thank you so much! This is one of the only tutorials in all of RU-vid that teaches about multitouch and fingerId
@usmanarshad855
@usmanarshad855 4 года назад
This is amazing i was searching for this from past 3 days and you just did it in about 10 min amazing you save me man amazing work just simple and clean You got a follower, I realize other just make a video and didn't explain stuff as clearly as you do. Keep up the good work man. Thumb up
@pressstart6864
@pressstart6864 4 года назад
Thanks for the very positive feedback. Glad I could help you :)
@bennettgodinho-nelson8717
@bennettgodinho-nelson8717 5 лет назад
Keep it up dude! I know for a fact you'll get the love you deserve sooner than later. Maybe a powerups video next?
@brainy3429
@brainy3429 2 года назад
Neat and clean tutorial and must-know information . Thanks a lot!
@syu9868
@syu9868 9 месяцев назад
Very brilliant and clearly explained! You saved me at least 2 days.
@alextreme98
@alextreme98 4 года назад
Thanks for this video, it's exactly what i was searching for :D
@hachihao1604
@hachihao1604 4 года назад
Very easy to understand! Thank you!
@frankypappa
@frankypappa 5 лет назад
great tutorial! thank you for it
@cartofsrl9589
@cartofsrl9589 3 года назад
Wow you are the Master! Thank you!
@nyscersul42
@nyscersul42 2 года назад
Just... Thanks dude!
@prathamesh_dalvi
@prathamesh_dalvi 5 лет назад
Hey Bro..Thank u Tutorial..
@MikeArcuri
@MikeArcuri 2 года назад
Nice video. I'm still way more comfortable with the old input system than the new one, and this explains multi-touch the old way! You essentially built a dictionary here from the list plus the touchLocation class. Maybe cleaner to just use Dictionary or Dictionary ?
@varunwahi715
@varunwahi715 2 года назад
Thank you so much!
@jonathangarciarodriguez1240
@jonathangarciarodriguez1240 5 месяцев назад
This was such a great tutorial! Thank you so much. I actually made mine in 3D, so I made a few modifications to your script. I'll drop it here in the comments in case anyone wants this result but in 3D :) using System.Collections; using System.Collections.Generic; using UnityEngine; public class multipleTouch : MonoBehaviour { public GameObject circle; public List touches = new List(); void Update () { int i = 0; while(i < Input.touchCount){ Touch t = Input.GetTouch(i); if(t.phase == TouchPhase.Began) { Debug.Log("touch began"); touches.Add(new touchLocation(t.fingerId, createCircle(t))); } else if(t.phase == TouchPhase.Ended) { Debug.Log("touch ended"); touchLocation thisTouch = touches.Find(touchLocation => touchLocation.touchId == t.fingerId); Destroy(thisTouch.circle); touches.RemoveAt(touches.IndexOf(thisTouch)); } else if(t.phase == TouchPhase.Moved) { Debug.Log("touch is moving"); touchLocation thisTouch = touches.Find(touchLocation => touchLocation.touchId == t.fingerId); thisTouch.circle.transform.position = getTouchPosition(t.position); } ++i; } } GameObject createCircle(Touch t){ GameObject c = Instantiate(circle) as GameObject; c.name = "Touch" + t.fingerId; c.transform.position = getTouchPosition(t.position); return c; } Vector3 getTouchPosition(Vector2 touchPosition) { return GetComponent().ScreenToWorldPoint(new Vector3(touchPosition.x, touchPosition.y, 20f)); } } If you want the circle (or whatever gameobject you have) to be bigger/smaller in the screen, just modify the "20f" in the getTouchPosition method. The other script stays the same though. Hope this helps!
@user-wr4gc1dg7n
@user-wr4gc1dg7n 5 лет назад
Thank you so much!! you saved me 😍😍
@pressstart6864
@pressstart6864 5 лет назад
잉 잉수 thank you for your support
@rajpolinovsky8350
@rajpolinovsky8350 3 года назад
THX!!! It's the beast video tutorial!!!!!!!!!!
@ismailefetekin
@ismailefetekin 2 года назад
Thanks 👏👏👏
@danieljayne8623
@danieljayne8623 3 года назад
Great information. Not that it matters in the grand scheme of things but I'm confused about the way you format code, particularly around casing and line breaks between functions. Did you start with a language other than c#?
@lexxynubbers
@lexxynubbers 5 лет назад
I would have thought a for loop would make more sense than while, and is very quick to implement with the for snippet. Otherwise, very useful series of tutorials.
@johna5099
@johna5099 5 лет назад
Hi, i like your tutorials. Can you make video of how to make Level progress bar(eg: - voodoo game Radial has it the bar move from left to right on top of the screen to indicate how much you left to complete that level) can you do that? Please keep making tutorials. You have the gift of teaching . Not all RU-vidrs have that. Thank you.
@IbizanHound2
@IbizanHound2 3 года назад
Thank you so much for the tutorial! Will this work with a touchpad connected to a PC through USB or it only works on mobile platforms?
@gregoryfenn1462
@gregoryfenn1462 5 лет назад
I feel like at 4:02, you just reinvented the concept of a for loop!
@pressstart6864
@pressstart6864 5 лет назад
haha, yeah I don't know why I wrote it like that haha. Thanks for pointing it out!
@karzweh6642
@karzweh6642 4 года назад
Hey! I would just like to say that I love your channel. I'm just starting to learn how to program for mobile. However, after following your instructions, I sometimes get a null reference exception when I have multiple fingers touching the screen and I remove some of them, is this me doing something wrong or is there a reason why this is happening?
@theresults4421
@theresults4421 5 лет назад
THE VIDEO MENTIONED AT THE ENDING
@Nekotico
@Nekotico Год назад
im working on the version 4 and im trying to figure out how it worked back in those days (cant use anything new cuz my actual pc at the momment)
@theresults4421
@theresults4421 5 лет назад
THANK YOU SIR,CAN U UPLOAD THE NEXT VIDEO FASTER IAM WAITING FOR IT
@pressstart6864
@pressstart6864 5 лет назад
The Results im taking a break this month but I’ll be posting something in January
@SrKiwiLoL
@SrKiwiLoL 5 лет назад
I also need the other video. There is no info on how to have a joystick and touch the screen at the same time. By any means is it done the same way as you did in this video?
@pressstart6864
@pressstart6864 5 лет назад
@@SrKiwiLoL Be patient, we're currently working on launching a new website and then consistent uploads will start back up in February.
@pedrohenrique-rc6iv
@pedrohenrique-rc6iv 2 года назад
in case I want to create different objects with each tap. What do I do?
@stevenarif1955
@stevenarif1955 4 года назад
Hello, i know this video been 1 year. I just wanna asking how to implemented drag and drop with this script? i'm beginner in programming but try best as i can but no luck. Thank you
@Trickerik
@Trickerik 5 лет назад
It's a good tutorial, but I can't finish it as I can't make out what's in the rest of the line of code you paste in at 5:51. What is it? :) Thanks.
@pressstart6864
@pressstart6864 5 лет назад
You can grab it from here: pressstart.vip/tutorials/2018/11/14/81/multiple-touch-inputs.html
@diegoRAM_
@diegoRAM_ Месяц назад
The movements come out the other way around, I move it to the left and it goes to the right, I move it up and it goes down
@stephanebouquet8653
@stephanebouquet8653 4 года назад
Hello. Great Tutorial. I have an issue with more than 5 simultaneous touches ==> they don't desappear anymore. I am testing on an iPhone 7+. I don't see anything in the code that could prevent displaying more than 5 touches. Is it a limitation of the phone ?
@SafetyRabbittt
@SafetyRabbittt Год назад
The iPhone and iPod Touch devices are capable of tracking up to five fingers touching the screen simultaneously. Ipad doesn't have such problem.
@charlesferry9465
@charlesferry9465 3 года назад
but location is world space how about specific location? reply please
@RoshanSingh-vu6si
@RoshanSingh-vu6si 4 года назад
will this work for 3d game also??
@sarathkumar-gq8be
@sarathkumar-gq8be Год назад
touchlocation list will give error of assembly language there is no namespace in C#
@noraholmberg2303
@noraholmberg2303 2 года назад
How to code the "getTouchPosition" for perspective camera?
@vatsoffice
@vatsoffice 9 месяцев назад
did you find out?
@pressstart6864
@pressstart6864 5 лет назад
Copy & Paste Source Code: pressstart.vip/tutorials/2018/11/14/81/multiple-touch-inputs.html
@dkordy
@dkordy Год назад
and what if unity dont recognize my device?!?
@muzammalhussain7869
@muzammalhussain7869 5 лет назад
Hello Sir, Nice work, i need your help about Unity please can you help me? i will wait, Thank you :)
@cyrasunny3884
@cyrasunny3884 5 лет назад
Please help this is a code which will transfer voice from one device to other This is pc code where we have to click R for rec. How to change this code so that i can use this for my mobile game when button is clicked using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using UnityEngine.Networking.NetworkSystem; using System.Text; using POpusCodec; using System.Collections.Generic; using System; [RequireComponent(typeof(AudioSource))] [RequireComponent(typeof(NetworkIdentity))] public class OpusNetworked : NetworkBehaviour { public FixedButton Rec; // device id of the microphone used to record sound public int micDeviceId = 0; // the audio source for the mic, used for recording sound AudioSource audiorecorder; // the audio source for playback, must not be the same as the audio recording audiosource [Header("add a different audioSource for the playback")] public AudioSource audioplayer; // buffers to receive and send audio data List micBuffer; List receiveBuffer; // size of a network package of opus, audio needs to be split in equal size packages and sent int packageSize; // decoder and encoder instances of opus OpusEncoder encoder; OpusDecoder decoder; // other values then stereo will not yet work POpusCodec.Enums.Channels opusChannels = POpusCodec.Enums.Channels.Stereo; // other values then 48000 do not work at the moment, it requires and additional conversion before sending and at receiving // also osx runs at 44100 i think, this causes also some hickups POpusCodec.Enums.SamplingRate opusSamplingRate = POpusCodec.Enums.SamplingRate.Sampling48000; bool recording = false; [Header("should the locally recorded sound be played locally as well?")] [SyncVar] public bool playLocally = false; public override void OnStartLocalPlayer() { Debug.Log("OpusNetworked.OnStartLocalPlayer: " + System.Environment.MachineName); base.OnStartLocalPlayer(); string value = System.Environment.MachineName; // + " - " + (Time.frameCount / 30).ToString(); Debug.Log("Update: " + System.Environment.MachineName + " send: " + value); } [ClientCallback] void Update () { // update if we send audio recording recording = (Input.GetKey (KeyCode.L)); SendData(); } // Use this for initialization void Start() { micBuffer = new List(); if (isLocalPlayer) { //data = new float[samples]; encoder = new OpusEncoder(opusSamplingRate, opusChannels); encoder.EncoderDelay = POpusCodec.Enums.Delay.Delay20ms; Debug.Log("Opustest.Start: framesize: " + encoder.FrameSizePerChannel + " " + encoder.InputChannels); // the encoder delay has some influence on the amout of data we need to send, but it's not a multiplication of it packageSize = encoder.FrameSizePerChannel * (int)opusChannels; //dataSendBuffer = new float[packageSize]; //encoder.ForceChannels = POpusCodec.Enums.ForceChannels.NoForce; //encoder.SignalHint = POpusCodec.Enums.SignalHint.Auto; //encoder.Bitrate = samplerate; //encoder.Complexity = POpusCodec.Enums.Complexity.Complexity0; //encoder.DtxEnabled = true; //encoder.MaxBandwidth = POpusCodec.Enums.Bandwidth.Fullband; //encoder.ExpectedPacketLossPercentage = 0; //encoder.UseInbandFEC = true; //encoder.UseUnconstrainedVBR = true; // setup a microphone audio recording Debug.Log("Opustest.Start: setup mic with " + Microphone.devices[micDeviceId] + " " + AudioSettings.outputSampleRate); audiorecorder = GetComponent(); audiorecorder.loop = true; audiorecorder.clip = Microphone.Start( Microphone.devices[micDeviceId], true, 1, AudioSettings.outputSampleRate); audiorecorder.Play(); } // playback stuff decoder = new OpusDecoder(opusSamplingRate, opusChannels); receiveBuffer = new List(); // setup a playback audio clip, length is set to 1 sec (should not be used anyways) AudioClip myClip = AudioClip.Create("MyPlayback", (int)opusSamplingRate, (int)opusChannels, (int)opusSamplingRate, true, OnAudioRead, OnAudioSetPosition); audioplayer.loop = true; audioplayer.clip = myClip; audioplayer.Play(); } [ClientCallback] // this handles the microphone data, it sends the data and deletes any further audio output void OnAudioFilterRead(float[] data, int channels) { if (recording) { // add mic data to buffer micBuffer.AddRange(data); Debug.Log("OpusNetworked.OnAudioFilterRead: " + data.Length); } // clear array so we dont output any sound for (int i = 0; i < data.Length; i++) { data[i] = 0; } } [ClientCallback] void SendData () { if (isLocalPlayer) { // take pieces of buffer and send data while (micBuffer.Count > packageSize) { byte[] encodedData = encoder.Encode (micBuffer.GetRange (0, packageSize).ToArray ()); Debug.Log ("OpusNetworked.SendData: " + encodedData.Length); CmdDistributeData (encodedData); micBuffer.RemoveRange (0, packageSize); } } } [Command] void CmdDistributeData(byte[] encodedData) { Debug.Log("OpusNetworked.CmdDistributeData: " + encodedData.Length); RpcReceiveData(encodedData); } [ClientRpc] void RpcReceiveData(byte[] encodedData) { if (isLocalPlayer && !playLocally) { Debug.Log("OpusNetworked.RpcReceiveData: discard! " + encodedData.Length); return; } Debug.Log("OpusNetworked.RpcReceiveData: add to buffer " + encodedData.Length); // the data would need to be sent over the network, we just decode it now to test the result receiveBuffer.AddRange(decoder.DecodePacketFloat(encodedData)); } // this is used by the second audio source, to read data from playData and play it back // OnAudioRead requires the AudioSource to be on the same GameObject as this script void OnAudioRead(float[] data) { Debug.LogWarning("Opustest.OnAudioRead: " + data.Length); int pullSize = Mathf.Min(data.Length, receiveBuffer.Count); float[] dataBuf = receiveBuffer.GetRange(0, pullSize).ToArray(); dataBuf.CopyTo(data,0); receiveBuffer.RemoveRange(0, pullSize); // clear rest of data for (int i=pullSize; i
@pressstart6864
@pressstart6864 5 лет назад
In your update function, you have: void Update () { // update if we send audio recording recording = (Input.GetKey (KeyCode.L)); SendData(); } recording appears to be a boolean, so you just need to set it true when the mouse is down. You'd basically just change this line to: recording = Input.GetMouseButton(0);
@cyrasunny3884
@cyrasunny3884 5 лет назад
Press Start thanks for the reply I mean if I clicked a button on the screen then it should start recording
@pressstart6864
@pressstart6864 5 лет назад
@@cyrasunny3884 again you just need to set recording to true, so create a function for the button press like: void recordButtonPress(){ recording = !recording; } Then set the button's click trigger to execute that function
@advait4484
@advait4484 3 года назад
8:25
@sseymour1978
@sseymour1978 2 года назад
Instead of getTouchLocation() I used: circle.transform.SetParent(canvasReference.transform); circle.transform.localScale = Vector3.one; circlel.transform.localRotation = Quaternion.Euler(Vector3.zero);
@dejoncage9286
@dejoncage9286 Год назад
Is there a way to make the touch and release a timer?