Unity 3D RayCast Collisions (In 2 Minutes!!)

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ธ.ค. 2024

ความคิดเห็น • 50

  • @TheRoyalSkies
    @TheRoyalSkies  3 ปีที่แล้ว +18

    This is something that I forgot to say, but I believe 1 Raycast is easier on your computer than 1 collider. I was told a long time ago to use Raycast instead of colliders if possible. (Correct me if I'm wrong on that though - ) Like, sometimes it's better to use 1 box collider instead of 7 Raycasts, but in a 1 to 1 battle, the Raycast is generally more efficient -
    CODE BELOW :
    {
    public float range = 5;
    void Update()
    {
    Vector3 direction = Vector3.forward;
    Ray theRay = new Ray(transform.position, transform.TransformDirection(direction * range));
    Debug.DrawRay(transform.position, transform.TransformDirection(direction * range));
    if (Physics.Raycast(theRay, out RaycastHit hit, range))
    {
    if (hit.collider.tag == "environment")
    {
    print("It's the Environment-");
    }
    else if (hit.collider.tag == "enemy")
    {
    print("It's the ENEMY!!!!!");
    }
    }
    }
    }

    • @IchigoFurryModder
      @IchigoFurryModder 3 ปีที่แล้ว +15

      Whether raycasting is better or not really comes down to the amount of data you're computing, a raycast is defined really with just two positions in world space, that's just 24 bytes, compare that to collision with a mesh, every individual vertex needs a position, thats 12 bytes, and it needs a normal direction which amounts to 24 bytes, remember, that's on a per vertex basis, you also need 3 ints for each triangle(because triangles are the 2D shape with the least amount of vertices, so its the easiest to compute so in games you wanna triangulate everything, no quads allowed in rendering stage, or collision solving), each int being a reference to a vertex, now obviously it also depends on the complexity and amount of data of the mesh, but as a general note it just wouldn't make sense for collision between meshes A and B to be faster than collision between mesh A and raycast C even if both meshes are a single triangle because it just has more data going into it, collision from mesh to mesh inherently *needs* more CPU cycles, it's like 1024+8 and 1024*1024, second case is just logically gonna need more time no matter what, and as for many raycasts being slower than a complex mesh and another complex mesh, not too complex but not a single triangle either, well, you naturally can't do ray to ray collision because they're infinitely thin, so it has to be ray to mesh, and you're computing the collision with the mesh for each ray, so you're solving the mesh's collision 7 times, granted with a simple ray, but still you're solving the mesh 7 times nonetheless.

    • @TheRoyalSkies
      @TheRoyalSkies  3 ปีที่แล้ว +9

      @@IchigoFurryModder Thanks for clearing that up. I'm sure I'm not the only who appreciates all the information in that comment -!

    • @Thesupperals
      @Thesupperals 3 ปีที่แล้ว +4

      From what I know about ray casting, it all depends on how you use them. For example, Ray casting isn't dependent on physics while colliders typically are. It always boils down to how smart and creative you are with very limited resources. So yes, while you are correct with the 1 to 1 comparison there are some limited variables which could otherwise hinder it's performance- such as the distance value.
      I personally am striving to learn how to program 3D modeling in C# so that I can reference those values via script and further reduce the usage of such properties to only a nibble per vertex that identifies itself before intersection with a face/tri, edge and vertex.

    • @IchigoFurryModder
      @IchigoFurryModder 3 ปีที่แล้ว

      @@TheRoyalSkies It's nothing, just spoke my mind there for the most part, and thanks for saying that, it's nice to hear stuff like that :)

    • @IchigoFurryModder
      @IchigoFurryModder 3 ปีที่แล้ว

      @@Thesupperals Yeah that's right, but I was talking about solving for raycasts and colliders in general, not just Unity's implementation that's actually just a PhysX wrapper, AKA, it's Nvidia's implementation lol, that's another thing, I've been talking about CPU cycles and whatnot, but PhysX barely does anything on the CPU, the actual engine runs on compute shaders in the GPU, so really when talking about specifically Unity, the amount of data is not *too* much of a concern because GPUs are all designed to crunch on lots of numbers at the same time, which things like graphics and physics benefit from, but you typically implement it on CPU because it can be a lot harder to do complicated stuff on the GPU since the logic from CPU programming doesn't translate *quite* right to the GPU, but do not think that just because a GPU is made to crunch numbers the amount of data won't matter, it still matters, just not the way you'd think, like I said, CPU logic doesn't quite translate to GPU logic, the amount of data does matter, but not so much because of the amount of cycles due to just how many entire cores GPU's have, it can be a few dozens of cores, not transistors or logic gates, the amount of data matters but how much it matters depends on the amount of video memory you have, the speed of the memory, and the bandwith of everything standing between the GPU and the CPU, which because of bottlenecking will be the bandwidth of the thing with the smallest bandwith, that will be the bandwidth of the memory itself, the graphics card and whatever PCI-E slot you inserted the card into, taking into account the configuration of the slots and the settings of the UEFI of course, also maybe anything you may have between the PCI-E and the card, like one of those weird adapters for plugging a graphics card to one of the tiny PCI-E slot laptops and AIO computers have for plugging Wi-fi cards, the ones that look like you could put an SSD into, which you can't, I tried.

  • @CoolCatCorbin
    @CoolCatCorbin 2 ปีที่แล้ว +2

    wowzas, finally someone who doesn't spit out 10 paragraphs of words explaining raycasting

  • @MAXmillium
    @MAXmillium 2 ปีที่แล้ว

    I've been stuck on trying to tell which player in a game won the battle and have been mucking about with colliders and testing directions for 2 weeks now. You solved my issue in 1min.
    Thank you.

  • @IchigoFurryModder
    @IchigoFurryModder 3 ปีที่แล้ว +4

    Hi, this is gonna be a long one, oh boy, and offtopic, it's on a package I'm working on, I want to share it here because I like this community and I think this could be useful to some people out there.
    I actually said something about this a few days ago, the package is TransformConstraints, and it's not terribly stable, it's in preview, I still gotta work a thing or two so you may have to go through a hoop to use it, but it's functional, and I'm honestly kinda burnt out so I wanted to just publish it as is, so I'm posting it here now, not the cleanest code either but it works.
    Anyway, the package is up on GitHub under the MIT license, which in a nutshell means you can derive anything from it and use it however you want as long as you explicitly state you did an include the license but don't quote me on that, look it up yourself because you should *never* take legal advice from random people on internet, and also I haven't used that license or read it in a while, I went off of memory there so it's probably not terribly accurate.
    ***A bit about why I'm working on this and some other stuff***
    I am aware Unity already does have a few constraint components, but the point of this package is that it's a single component, and the constraints are in a list, that way you can give them an order of execution on a per-object basis, you can also make your own constraints that you can reuse by inheriting from the ConstraintSolver class and implementing a couple methods.
    Do keep in mind, the package is currently in preview, as I said, and it'll stay like that for a while, until I update the architecture to have stable transform resetting, though if anyone wants to try to look into it I'd appreciate it a lot, the code isn't the cleanest, I know, but I think it's simple enough that you can understand it if you take a moment to read it, and besides, I'm not *expecting* the community to go fix it, I'm planning to do that myself later, I'm just saying that if someone does look into it or even fix it, that'd be very *very* much appreciated.
    I have some triple forward slash documentation, it's not finished but it's some help, one file that does have finished documentation is SerializedData.cs, this file is using Unity's JsonUtility class to serialize and deserialize classes manually, that in combination with the ISerializationCallbackReceiver interface gives me the ability to serialize abstract classes so they actually get saved by Unity to scenes and prefabs and not get lost into oblivion, you can steal that class if you want; this class is in it's own assembly, this is because I wanted to have a separate package with utilities, and use it as a dependency, but I couldn't find a way to get dependencies working, Unity would just say that the dependency is invalid, though installing it independently did work, except when installing the constraints package it would tell me that the packages were in conflict with each other for some reason, so that's something I wanted to mention.
    ***Installation guide***
    Since I can't upload images in comment sections, I'll have a set of links at the bottom, and when I need to share an image at some point for whatever reason, I'll refer to a link at the bottom.
    To install the package you should use the Unity Package Manager (UPM).
    First things first, go to the GitHub page and get the link to the git file, which you can find in the big green button labeled "Code" [figure 1].
    Over in UPM, which you can pull up by going to Window/Package Manager on the bar at the top of the Unity Editor, click on the button with a plus sign and select "Add package from git URL..." [figure 2], and Unity will show you a text box where you can input a URL to the git file on the internet, you wanna paste the link you got from the GitHub page there and press the Add button, this will automatically install the package in your project provided there isn't a conflict with some other package, which is unlikely, and it should just works as is.
    Once the package is installed, you can add a ConstraintObject component to any game object you want, you'll find three buttons [figure 3], the first button is an attempt to combat the issue I was talking about resetting the transform, it's not a permanent solution, but again it's a preview package, anyway, the other two buttons are respectively for deleting and adding constraints, the add constraint button will display a context menu that displays every class that derives from the ConstraintSolver class [figure 4], you can select any one of them to add it to the stack, the delete constraint button deletes the constraint that's at the bottom of the stack.
    Every constraint has an slider, this is an influence percentage, and there's also a button to hide the constraint, and right below the name there's all the parameters for that specific constraint [figure 5].
    ***On making your own constraints, not super detailed, that'll later on be in the GitHub's wiki***
    You can make your own constraints just by inheriting the abstract class ConstraintSolver, implementing these virtual methods:
    void Solve(Transform), which is where the actual logic of the constraint is.
    string MenuPath(), which is the path of the context menu that comes up when adding a new constraint, it works exactly like a folder structure.
    void OnInspectorGUI(bool), which is what will render the constraint in the inspector, when implementing it, it's recommended to call base.OnInspectorGUI(bool), if you do, pass false to the arguments, and afterwards call EditorGUILayout.EndHorizontal() , then, check for the foldout variable being true, and in that if statement put the entirety of the code to render any elements you want, like another slider or something, and if you are calling base.OnInspectorGUI(bool) always call EditorGUILayout.EndFoldoutHeaderGroup() at the very end of the method.
    Something else to have in mind, which I haven't tested yet, you *might* wanna implement the constructors.
    For some more details you can look into DefaultConstraints.cs for examples on how to use ConstraintSolver.
    ***LINKS***
    Figure 1: cdn.discordapp.com/attachments/446460216834523156/822965743850487868/unknown.png
    Figure 2: cdn.discordapp.com/attachments/446460216834523156/822964401958027294/unknown.png
    Figure 3: cdn.discordapp.com/attachments/446460216834523156/822988342798712832/unknown.png
    Figure 4: cdn.discordapp.com/attachments/446460216834523156/822989522597052456/unknown.png
    Figure 5: cdn.discordapp.com/attachments/446460216834523156/822989668961615893/unknown.png
    GitHub page: github.com/ChloeZamorano/IxC.TransformConstraints

  • @Thesupperals
    @Thesupperals 3 ปีที่แล้ว +8

    WOO! RAY CASING! MY FAVORITE SUBJECT!! Side note: Wouldn't it have been wise to teach those about using multiple RayCast perspectives (X Y and Z)? This can help with "feet touching the ground correction" (100% like procedural movement) as the cast is acting as a bool operand and incorporate other amazing tools.

  • @sergeysafonov2461
    @sergeysafonov2461 3 ปีที่แล้ว +4

    Ok. Let's walk through the code. Firstly transform.forward is already in world space (always). So it does not need to be worldspaced more. You were lucky because your cube had no parent so localspace==worldspace. So your ray should be just new Ray(transform.position, transform.forward*range). Secondly, and it's performance point, everything related to collisions better be done with layers, not tags (or filter by tags after layers filtering). So you better use layermasks for 'vision' of your cube. Physics.Raycast() has layermask as one of parameters. But for tutorial it is ok to use just tags. And even if you use tags it's better to make them public varibles not to bother with code while tags renaming or any tags rearranging. But again, for tutorial purpose it's ok too :)

  • @jcd9456
    @jcd9456 3 ปีที่แล้ว +1

    Quick, Concise, and helpful. Thanks

  • @mageofmagic3731
    @mageofmagic3731 2 ปีที่แล้ว

    You're an absolute saint

  • @Ziprava42
    @Ziprava42 7 หลายเดือนก่อน

    That's what I needed it. Thank you!👍

  • @masonwheeler6536
    @masonwheeler6536 3 ปีที่แล้ว +4

    There's a simpler way than using transform.TransformDirection and Vector3.forward. A Transform has a "forward" property built-in, so you can just say:
    void Update()
    {
    Ray theRay = new Ray(transform.position, transform.forward);
    Debug.DrawRay(transform.position, transform.forward * range);
    if (Physics.Raycast(theRay, out RaycastHit hit, range))
    ...
    Also, the second argument to "new Ray" is a pure direction, so there's no need to multiply it by range; the range goes in the call to Physics.Raycast. (Note that this is not true for Debug.DrawRay. Yay for consistency!)

  • @alexandresajus
    @alexandresajus ปีที่แล้ว

    Excellent video, concise, just what I needed

  • @SansTheSamurai
    @SansTheSamurai ปีที่แล้ว

    Thank you this was a quick and comprehensive tutorial, unlike most unity tutorials. Thank you for not wasting my time, and actually helping with the problems I was having (again unlike other unity tutorials)!

  • @j.lucassantos4223
    @j.lucassantos4223 3 ปีที่แล้ว

    I'm a Brazilian person and that kinda video (pretty great 😁) we doesn't has in Portuguese. Normally the best videos are in English.
    Man U are sooo goooodd and I'm very happy for having found Your channel.
    Thanks man!!
    Have a fantastic day and I see U round😁
    Portuguese:
    Sou brasileiro e esse tipo de vídeo (ótimos 😁) não encontramos aqui em português. Normalmente ou melhores vídeos são em inglês.
    Cara, você é taoooo booomm e estou muito feliz por ter encontrado seu canal.
    Obrigado cara!!!
    Tenha um dia fantástico e eu te vejo por aí😁

  • @sillyninja65
    @sillyninja65 ปีที่แล้ว

    easy fast and to the point. fantastic

  • @kretoskim8555
    @kretoskim8555 10 หลายเดือนก่อน

    This is GOLD! Thank you!!!!!

  • @jasonwilliams8730
    @jasonwilliams8730 3 ปีที่แล้ว +1

    Great tutorial

  • @kriegs8315
    @kriegs8315 3 ปีที่แล้ว +1

    yes

  • @rohan6454
    @rohan6454 3 ปีที่แล้ว +1

    Nice stuff

  • @IchigoFurryModder
    @IchigoFurryModder 3 ปีที่แล้ว +2

    I don't use Ray variables, I just pas the ray data to the method directly, it has overloads for that, I usually use the overload Raycast(Vector3 origin, Vector3 direction, float maxDistance, int layerMask), the origin is where the ray starts, you can think of the ray as a particle, and the direction is as the name implies the *direction* the ray goes towards, all this is in world space by the way, that's why he uses the TransformDirection method, anyway, the reason I emphasize that it's a direction has to do with math, basically it's not at all the position where the ray ends, you can look at some tutorial from, I don't know, Brackeys maybe has one, on vectors, but anyway the point is that you're supposedly passing a normalized vector(I don't know if the raycast methods normalize it internally that's why I say supposedly, maybe not the right term but you get the idea), and if you don't know what that is, you can look it up, it's a simple concept, but anyway, pay attention to the overload because the next parameter is called maxDistance, not distance, you can leave it alone or set it to Mathf.Infinity and then anything in front of the ray, no matter how far away will indeed be registered, the next parameter is the layer mask, so if you know what layers are, basically if instead of an int you pass a LayerMask type, in the inspector you can select some layers, and the ray will only collide with stuff in those layers which can be very useful to exclude certain object, since using tags can add overhead when you use it a lot, even if you use the CompareTag function instead of the painfully slow string == string comparison.
    Also note that for some reason Debug.DrawRay expects you to input an end position, instead of a direction and then a distance like the actual raycast stuff does, I don't know why, that's just inconsistency, but that's something to look out for.

    • @irql2
      @irql2 3 ปีที่แล้ว +1

      That's one hell of a run on sentence. You gotta work on that if you want anyone to read that. Its damn near gibberish.

    • @IchigoFurryModder
      @IchigoFurryModder 3 ปีที่แล้ว

      imawalkingscientificpaperialwayshavelongsentencesexplainingthingstodetail

    • @irql2
      @irql2 3 ปีที่แล้ว +2

      I wonder if Royal skies has any 2 minute videos on 3rd grade grammar. If not, there’s certainly an audience for it. ;)

  • @kris8286
    @kris8286 3 ปีที่แล้ว +1

    Awesome.

  • @Daitomodachi
    @Daitomodachi 3 ปีที่แล้ว

    Question. I thought using Raycast in an update loop is costly?

    • @NemesisTWarlock
      @NemesisTWarlock 3 ปีที่แล้ว

      It depends on how many raycasts you do, though unless you're throwing *thousands* of raycasting objects, you're usually fine.

  • @VerzatileDev
    @VerzatileDev ปีที่แล้ว

    Thank you!

  • @christopherhappel9679
    @christopherhappel9679 2 ปีที่แล้ว

    you da man

  • @husbando_maker1856
    @husbando_maker1856 3 ปีที่แล้ว +1

    Is it possible could you do a scultping tutorial like cause i wanna know how to make a full figure 😊 there not alot of sculpting tutorials for blender so i just wanted to ask

    • @TheRoyalSkies
      @TheRoyalSkies  3 ปีที่แล้ว +1

      We'll be getting into sculpting after Unity :)

  • @blessedponica8030
    @blessedponica8030 ปีที่แล้ว

    Thank you a lot!

  • @fl4bzgam3s41
    @fl4bzgam3s41 ปีที่แล้ว

    Thank you :)

  • @kamillatocha
    @kamillatocha 3 ปีที่แล้ว

    so now just how to get the hit position in world space so i can place an object there

  • @serdarozgen4636
    @serdarozgen4636 2 ปีที่แล้ว

    thanks!!!!!🐯

  • @unknownid530
    @unknownid530 ปีที่แล้ว

    I just wanted to detect a opject in front of me box collider didnt do the job well so i decided to use ray cast tnx for the tutorial

  • @Khoura
    @Khoura 3 ปีที่แล้ว +1

    Dude, what is that outro song? I need it!

    • @TheRoyalSkies
      @TheRoyalSkies  3 ปีที่แล้ว

      "One More Win" from Ridge Racer Type 4 :)

  • @IchigoFurryModder
    @IchigoFurryModder 3 ปีที่แล้ว +1

    Now I'm just pumping a bit of extra algorithm j̷ ̶u̷ ̸i̶ ̶c̴ ̷e̴ ̵s̷ here, don't mind me.

  • @thedude4039
    @thedude4039 3 ปีที่แล้ว +1

    0:06 Stop. It's not a collider.

  • @arionpaul6208
    @arionpaul6208 3 ปีที่แล้ว

    Plz on auto generate lightning

  • @alanoosgames9206
    @alanoosgames9206 3 ปีที่แล้ว

    Thx :D

  • @sk.mahdeemahbubsamy2857
    @sk.mahdeemahbubsamy2857 3 ปีที่แล้ว +2

    Dude make a tutorial with unity's Bolt i dont have a big brain to understand coding.....

    • @IchigoFurryModder
      @IchigoFurryModder 3 ปีที่แล้ว +2

      That's funny to me because visual scripting is kinda hard for me, I have a much easier time with plain text, except when we talk about shaders, visual *shader* scripting ftw!

  • @karlv_4373
    @karlv_4373 3 ปีที่แล้ว +1

    haha im first