- Home /
Is it correct way to draw sprite between two points?,Is it the best way to draw prefab between 2 points?
Hello! I want to draw sprite between two points in 2d space. I have prefab with small scaleY value. So I just draw my prefab in the center between two points and then change scaleX value in order to fill all space between two points. My code is:
//draw obstacle between two points
Vector3 center = Vector3.Lerp(from, to, 0.5F);
var direction = to - from;
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
var obj = Instantiate(obstacleObject, center, Quaternion.AngleAxis(angle, Vector3.forward));
//scale it between two points
var boundsSize = obj.GetComponent<SpriteRenderer>().bounds.size;
var scaleXKoef = Vector2.Distance(from, to) / Math.Max(boundsSize.x, boundsSize.y);
var localScale = obj.transform.localScale;
obj.transform.localScale = new Vector3(localScale.x * scaleXKoef, localScale.y,localScale.z);
Is it the best way to solve my issue? I'm not particularly sure about the part where I get Math.Max between boundSize.x and boundSize.y. Looks pretty tricky.
As this is not really an answer to the question, so ill make it a comment. Simply said, if this code works for you, it is good. In my opinion, you handle the rotation of the object and the positioning very well. $$anonymous$$aybe if someone else would write the same script it would look very different. But no one is the same. So I think it is good, there is no weird code to make it work, it is straight forward. Only thing I would change is don't use var, but the actual type, but that's just a personal style. When your scripts keep growing bigger and bigger at some point you don't know what var actually means. Learning to write the correct type will help you a lot in the future.
Your answer
Follow this Question
Related Questions
Scaling GameObjects by Screen Resolution 0 Answers
Sprite renderer scaling 0 Answers
Replacing and stacking shaders for some objects 1 Answer
Best practices - Model, animation and material naming 3 Answers