I am doing an attempt to make a 3D snake game, as an experiment but I am still a beginner. I have a Sphere
that I wish to dynamically resize to be, let's say, the 20th part of the width of this Plane
. How can I do this? I thought to find the size of the Plane
first. I also thought to use Screen.width
and Screen.height
because in my actual project the Plane
is almost the size of the screen, but from what I found the Transform
class does not have a way to resize it to a specific dimension in pixels.
Using the code below I do not get this work, but I also see that the Sphere
becomes a black circle because of the only instruction in the Start
method.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Attached to the Plane
public class SphereResizer : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// what should I put here?
GameObject.Find("Sphere").transform.localScale = new Vector3(1f, 1f);
}
// Update is called once per frame
void Update()
{
}
}
Here is the GitHub repository.
Thank you.
Answer
As this question is kinda 2 questions in one, I'm going to answer the one that I think is the root of your problem (scale sphere relative to plane). Because if I read this correctly, the pixel part sounds like you only want to do that because you couldn't find the solution to your original problem.
In Unity, a position is based on 'units'. a 'unit' doesn't have a set real world scale, it is just a number. As in, if you want a unit to be a mm, you pretend it is a mm. If you want it to be an inch, you pretend it to be an inch. (if you have UI with rendermode set to screen space overlay, it pretends 1 unit is 1 pixel). Note however that the physics engine is by default configured so that 1 unit == 1 meter in the real world. The grid that is drawn in the scene view is 1x1 unit, 10x10 units or 100x100 units (depending on zoom level).
How much pixels this one unit actually is depends on the camera used to render it, and there could even be 2 cameras rendering the same 3D object, resulting in the same object to be 2 different sizes in pixels on 2 different cameras.
The default cube and sphere, with a scale of [1,1,1] take up 1 unit in each axis.
The default plane, with a scale of [1,1,1] and not rotated takes up 10 units in x and z. And well, its a plane, so basically nothing in y...
So by default 10 spheres fit on a plane, so if you want to fit 20 spheres on a plane, you'd need to set the sphere scale to [0.5, 0.5, 0.5].
Also note, that you are giving the Vector3 constructor 2 parameters instead of 3. Meaning the z defaults to 0, resulting in your black sphere. So if you'd set the z aswell like this:
GameObject.Find("Sphere").transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
it should work better.
Also, you'd might want to consider using a quad instead of a plane... As that one by default takes up 1 unit in x/y. Which might just make it more intuitive for you...
No comments:
Post a Comment