• Advertisement
Sign in to follow this  

Unity Ray Pixel collision

This topic is 1637 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys


Ive been working on a project involving  ray  collision  with a multitextured terrain(2D heightmap)  the ray method(below) not only returns the triangle intersected but the uv(barycentric) coordinates as well but during research for my project I came across  a post from the unity website(link below) that had to do with  ray pixel intersection and wondered if I should implement that instead, so the question that Im asking is which of the two is better. should I stick with the ray uv coordinate method or go with an XNA version of the ray pixel collision.










unity ray pixel post










 the intersect method Ive been working with

public   bool RayTriangleIntersect(Vector3 ray_origin, Vector3 ray_direction,
                    Vector3 vert0, Vector3 vert1, Vector3 vert2,
                    out float? t, out float u, out float v)
            t = 0; u = 0;  v = 0;

            Vector3 edge1 = vert1 - vert0;
            Vector3 edge2 = vert2 - vert0;

            Vector3 tvec, pvec, qvec;
            float det, inv_det;

            pvec = Vector3.Cross(ray_direction, edge2);

            det = Vector3.Dot(edge1, pvec);

            if (det > -0.00001f)
                return false;

            inv_det = 1.0f / det;

            tvec = ray_origin - vert0;

            u = Vector3.Dot(tvec, pvec) * inv_det;
            if (u < -0.001f || u > 1.001f)
                return false;

            qvec = Vector3.Cross(tvec, edge1);

            v = Vector3.Dot(ray_direction, qvec) * inv_det;
            if (v < -0.001f || u + v > 1.001f)
                return false;

            t = Vector3.Dot(edge2, qvec) * inv_det;

            if (t <= 0)
                return false;


            return true;

also a youtube link to a project called rigs of rods to give a visual of the effect Im working on,

which is to have  a vehicle shoot out certain particles(dirt debris,grass debris,etc,..) based on

the texture its riding over.







Share this post

Link to post
Share on other sites

yet another option:


the pickray example in the directx sdk's. 


its probably the one that XNA's is based off of.


is it necessary to cast a ray?  there's no other way to know what texture is at location x,z  (the vehicle's location)? i take it the ground mesh is just a big textured mesh, with no underlying map, and you only have the artwork geometry to work with?

Share this post

Link to post
Share on other sites

i take it the ground mesh is just a big textured mesh, with no underlying map, and you only have the artwork geometry to work with?



Thanks for responding Norman,what would be the best type of terrain for this effect, right now Im using the shader based drawn terrain from riemers( http://www.riemers.net/eng/Tutorials/XNA/Csharp/series4.php)but would another approach do the job, like for example texture mapping(https://en.wikipedia.org/wiki/Texture_mapping),and what type of map do you think was used in this other youtube link below.



ultimate ninja storm






Thanks again

Share this post

Link to post
Share on other sites

right now Im using the shader based drawn terrain from riemers( http://www.riemers.net/eng/Tutorials/XNA/Csharp/series4.php)


a quick look at that link reveals that they are procedurally creating a large ground mesh, using a bitmap as the heightmap. and they are using the height at a given location to determine the blending weights of 4 textures they use, blending at most two together at once.


you would use a function similar to the one that maps height to blending weights, to map height to the closest single texture (the texture with the highest weight). that texture would determine the particle type to be emitted (mud, dust, gravel, etc). in border cases where the weights were equal, you'd choose some convention such as always going with the texture used for the "higher" altitude.


a function that maps from location to height to texture to particle type would get you just what you want: a function that maps from location to particle type based on underlying texture.


your heightmap function already does the location to height mapping.


you already know what texture you want to map to what kind of particle.


all you have to do is mod a copy of "height to blend weights" to create your "height to texture" function.





what would be the best type of terrain for this effect,


i don't quite follow....


do you mean the best type of terrain data structure?


in your case, the data structure is a bitmap heightmap, from which a ground mesh is procedurally generated, and from which texture blend weights are procedurally generated (on the fly apparently).


the downside of texture blend weights procedurally generated from a bitmap height map (on the fly) is that you have no "map" where you can just look up the texture at x,z and immediately create the appropriate type of particle emitter.. you must calculate the texture at x,z (on the fly) every time.   the workaround (if needed) is to implement an underlying map that you generate when you generate the mesh. in the underlying map, you calculate (one time only) and store the texture (and thus particle type emitted) at each location. 


an underlying map might take the form of a 2d array of bytes, with values of 0 through 3 indicating which texture is dominant (heaviest blend weight) and therefore which particle type to emit. the look-up function would do something like take x,z and convert them to ints, then used those int values as the array[x][z] indices to return a texture/particle type ID number 0 through 3. note that such a look-up table/map could get large. a 100x100 mesh would use an underlying map of 100x100 = 10,000 bytes. 

a 1000x1000 mesh would be 1 million bytes. and a 10,000x10,000 mesh would be 100 million bytes for the underlying map.


i personally use a "pattern map" to determine what ground texture goes where. a pattern map is just a small underlying map as described above. the difference is that a pattern map is only two times maximum visual range in size, instead of the size of the entire ground mesh, and gets repeatedly tiled across the ground mesh. the size is chosen to be as small as possible (to save ram), while being big enough that no repeating patterns due to tiling are ever visible from the camera's location while looking in all directions. my ground quads are 10x10, and my ground texture pattern map is 800x800. so the ground texture tile ID pattern map covers 80x80 quads, and only requires an 80x80= 6400 byte array. i use a single ground texture tile ID pattern map for all terrain types. i use 4 other pattern maps to place things like rocks, trees, berry bushes, fruit trees, and rock outcroppings. values in the ground texture pattern map are a simple ground texture tile set ID number 0 through 3. there are seamless ground texture tile sets (currently 4 tiles per set) for each terrain type. terrain type from the world map tells me the ground texture tile set used. the pattern map tells me which ground texture in the tile set is used at a given x,z location.


a pattern map lets you use seamless ground texture tile sets to reduce moire' patterns which you can get with just a single seamless ground texture tile (as seen in oblivion with distant ground textures). 


texture blending / splatting is another way to reduce or eliminate moire' patterns.




would another approach do the job, like for example texture mapping(https://en.wikipedia.org/wiki/Texture_mapping),


weighted texture blending (what you're doing) is already an advanced form of texture mapping. plain old texture mapping would just draw a single texture, not do a weighted blending of two textures.




what type of map do you think was used in this other youtube link below.


unfortunately, i'm on a 3g cell modem out in the boonies with marginal signal (1xrtt protocol usually - think dialup + intermittent signal loss), so streaming video isn't really happening for me.   : (


it drives me crazy, as i've become addicted to Korean historical dramas like "Faith" and "Iron Empress" on hulu.com.    <g>

Edited by Norman Barrows

Share this post

Link to post
Share on other sites



I was just about to give up on the heightmap idea and before reading your response  I  wrote a post about using a textured quad for a terrain instead(below), sorry about that, didnt want to come across as ungrateful for all of the help youve given me,but I will be putting the info you gave me to good use.






                                                   Thanks again laugh.png

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By 3dmodelerguy
      So I am building a turn based rogue-like (think CDDA). The game is going to have a very large map (up to 1000's x 1000's) however to alleviate most of that I obviously can't render everything so there will just be render a certain radius around the player and just load in and out data as the player moves.
      The next major system I am prototyping is making interactive tiles destructible and pretty much everything will be destructible besides basic landscape (cars, doors, windows, structures, etc. will be destructible)
      While I am only rendering a certain amount of tiles around the player, I want to keep the amount of colliders active at one time to be as small as possible for performance and currently the tilemap tool I use automatically merges colliders together.
      So instead of creating a separate colliders for each of these tiles and having the destructible behavior tied to that object (which my tilemap tool would allow me to do) I was thinking that I would store an array of all the X and Y locations for the interactive tilemap layer and let the tilemap manage the colliders. 
      Then when I hit a collider on the interactive tilemap layer, instead of of getting the behavior for how to deal with the destruction for that tile from that game object, I would pull it from the array I mentioned earlier based on the tile I attempt to interact with which I already have.
      Does this sound like a good approach? Any other recommendations would be welcomed.
    • By NDraskovic
      Hey guys,
      I have a really weird problem. I'm trying to get some data from a REST service. I'm using the following code:
      private void GetTheScores() { UnityWebRequest GetCommand = UnityWebRequest.Get(url); UnityWebRequestAsyncOperation operation = GetCommand.SendWebRequest(); if (!operation.webRequest.isNetworkError) { ResultsContainer rez = JsonUtility.FromJson<ResultsContainer>(operation.webRequest.downloadHandler.text); Debug.Log("Text: " + operation.webRequest.downloadHandler.text); } } The problem is that when I'm in Unity's editor, the request doesn't return anything (operation.webRequest.downloadHandler.text is empty, the Debug.Log command just prints "Text: "), but when I enter the debug mode and insert a breakpoint on that line, then it returns the text properly. Does anyone have an idea why is this happening?
      The real problem I'm trying to solve is that when I receive the text, I can't get the data from the JSON. The markup is really simple:
      [{"id":1,"name":"Player1"},{"id":2,"name":"Player2"}] and I have an object that should accept that data:
      [System.Serializable] public class ResultScript { public int id; public string name; } There is also a class that should accept the array of these objects (which the JSON is returning):
      [System.Serializable] public class ResultsContainer { public ResultScript[] results; } But when I run the code (in the debug mode, to get any result) I get an error: ArgumentException: JSON must represent an object type. I've googled it but none of the proposed solutions work for me.
      Also (regardless if I'm in the debug mode or not) when I try to do some string operations like removing or adding characters to the GET result, the functions return an empty string as a result
      Can you help me with any of these problems?
      Thank you
    • By nihitori
      The Emotional Music Vol. I pack focuses on beautiful and esoteric orchestral music, capable of creating truly emotive and intimate moods. It features detailed chamber strings, cello and piano as the main instruments, resulting in a subtle and elegant sound never before heard in video game royalty-free music assets.

      The pack includes 5 original tracks, as well as a total of 47 loops based on these tracks (long loops for simple use and short loops for custom / complex music layering).

      Unity Asset Store link: https://www.assetstore.unity3d.com/en/#!/content/107032
      Unreal Engine Marketplace link: https://www.unrealengine.com/marketplace/emotional-music-vol-i

      A 15 seconds preview of each main track is available on Soundcloud:
    • By RoKabium Games
      Another one of our new UI for #screenshotsaturday. This is the inventory screen for showing what animal fossils you have collected so far. #gamedev #indiedev #sama
    • By eldwin11929
      We're looking for programmers for our project.
      Our project is being made in Unity
      -Skills in Unity
      We're looking for programmers who can perform a variety of functions on our project.
      Project is a top-down hack-and-slash pvp dungeon-crawler like game. Game is entirely multiplayer based, using randomized dungeons, and a unique combat system with emphasis on gameplay.
      We have a GDD to work off of, and a Lead Programmer you would work under.
      Assignments may include:
      -Creating new scripts of varying degrees specific to the project (mostly server-side, but sometimes client-side)
      -Assembling already created monsters/characters with existing or non-existing code.
      -Creating VFX
      -Assembling already created environment models
      If interested, please contact: eldwin11929@yahoo.com
      This project is unpaid, but with royalties.
      Additional Project Info:
      Bassetune Reapers is a Player-verus-Player, competitive dungeon crawler. This basically takes on aspects of dungeon crawling, but with a more aggressive setting. Players will have the option to play as the "dungeon-crawlers" (called the 'Knights', or "Knight Class", in-game) or as the "dungeon" itself (literally called the 'Bosses', or "Boss Class", in-game). What this means is that players can choose to play as the people invading the dungeon, or as the dungeon-holders themselves.
      Key Features:
      -Intense, fast-paced combat
      -Multiple skills, weapons, and ways to play the game
      -Tons of different Bosses, Minibosses, creatures and traps to utilize throughout the dungeon
      -Multiple unique environments
      -Interesting, detailed lore behind both the game and world
      -Intricate RPG system
      -Ladder and ranking system
      -Lots of customization for both classes s of customization for both classes
  • Advertisement