0
\$\begingroup\$

Rookie here, still learning the basics of Unity.

I've been using a quad as a cursor sitting flat on top of a hilly terrain mesh. I've been getting the terrain angle by raycasting down at all four corners of the quad and finding where it hits the floor, then editing the quad vertices to shape it to the terrain angle. Probably not the ideal way but it works great for what I needed.

So the next step is replacing it with a sprite. I changed from quad to a sprite renderer, and added a little animation to it. I went to edit the vertices and the setup is completely different (it seems to have 20+ vertices now instead of 4).

I did notice the SpriteRenderer has 4 triangles, but the points are Vector2s rather than Vector3, so I guess that won't work either since I'm applying it to a 3d world?

Can anyone with experience point me in the right direction with this?

\$\endgroup\$
1
  • \$\begingroup\$ I suspect that displacing the vertices is not the best way to achieve this effect. Can you show us an example of what you want to create so we can propose solutions that might be simpler than mesh editing? \$\endgroup\$ – DMGregory Jun 26 '20 at 23:45
0
\$\begingroup\$

It sounds like you should just rotate the sprite instead of manipulating individual vertices. We can easily do this using the normal vector. This code should accomplish what you want and only needs three input points.

//compute the normal vector
var a = points[0].position;
var b = points[1].position;
var c = points[2].position;
var side1 = b - a;
var side2 = c - a;
var normal = Vector3.Cross(side1, side2).normalized;

//sprite faces along normal
sprite.rotation = Quaternion.LookRotation(normal);
//position sprite at the median between the three points
sprite.position = (a + b + c) / 3f;

Sprite renderers are one-sided, so you'll probably need a little bit of extra code to ensure the normal isn't reversed. Sprites are visible from their back side, so you actually want the sprite's transform to be pointed away from the camera. Or you can avoid this by putting two sprites, facing opposite directions, inside the same GameObject, so that one of the two sides is always facing the camera.

There are very few situations where you would need to manipulate the individual vertices of an object from code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.