Hi Everyone I am new to c# and unity i am trying to create a coins at height levels but if the coin is above a certain height I need to create a platform.
This is all working well when the ground level is at height 0 so y=0
but I don’t want a flat level so i created a function to return the y value of the floor but it is returning values of -1.86 none of the floor is below 0?
here is the function so i am feeding if a float of x where the coin will be created on the x axis any help would be great
float DisFromGround(float ob)
{
int l = LayerMask.GetMask("Ground");
float distanceToGround;
Vector2 pos= new Vector2 (ob,20);
var hit= Physics2D.Raycast(pos, -Vector3.up,20,l);
distanceToGround = hit.transform.position.y;
Debug.Log(hit.transform.position+" hit pos");
Debug.DrawLine(pos, hit.point, Color.red, 1);
return distanceToGround;
}
I tried looking at this last night when I couldn’t sleep, and couldn’t wrap my head around what you were doing. I figured I must’ve just been tired… But looking at it again today, I’m still a bit confused.
In particular, why are you passing a Vector3 to the Physics2D.Raycast function? And does this not throw an error?
Anyway, Physics2D.Raycast returns a Physics2D struct. That struct contains a transform property that gives the transform of the object that was hit, but not necessarily the point that it was hit at. I’m guessing that you want to actually be accessing the hit.point property, which is a Vector2 you can just grab the Y of.
It does not throw an exception but i did notice since posting that i was using a vector3 mainly because i copied a pasted from another example . i will try what you have suggested and let you know thanks for the advice
Thanks for the advice that is now working a treat. Sometime when you are looking at a issue its really experience you need which I am lacking so i appreciate your help on this