英文:
How can I fix the issue of my road object being smaller than expected in Unity?
问题
Creating and stretching an object is not working properly.
我正在尝试在Unity中为2D顶视项目创建道路系统。流程如下:
- 用户在屏幕上点击,预览线出现
- 预览线跟随鼠标光标移动
- 第二次点击后,端点设置,线条转换为与线条相同大小和位置的游戏对象。
一切都正常,直到进行变换操作,基本上代码创建了对象,但比预期要小得多。以下是一些截图:
预览线按预期工作
第二次点击后创建的对象(前一个截图上的预览线)
英文:
Creating and stretching an object is not working properly.
I am trying to create a road system for a 2D top-down project in Unity. The process is simple:
- User clicks on the screen, preview line appears
- Preview lines follows the mouse cursor
- After the second click endpoint is set and line transforms into a gameobject with the same size and position as a line.
Everything works until transformation, basically code creates the object, but it's much smaller than expected. Here are some screenshots:
Preview line works as expected
Object created after second click (preview line on previous screenshot)
using UnityEngine;
public class RoadBuilder : MonoBehaviour
{
public GameObject roadPrefab; // Prefab to instantiate the road
public LineRenderer previewLine; // LineRenderer to show the temporary road preview
private Vector2 startingPoint; // Starting point of the road
private Vector2 endingPoint; // Ending point point of the road
private bool isBuildingRoad; // Flag to indicate if the user is currently building a road
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (!isBuildingRoad)
{
// Start building road
isBuildingRoad = true;
startingPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
previewLine.positionCount = 2;
previewLine.SetPosition(0, startingPoint);
previewLine.SetPosition(1, startingPoint);
}
else
{
// Finish building road
endingPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CreateRoad(startingPoint, endingPoint);
isBuildingRoad = false;
previewLine.positionCount = 0;
}
}
else if (isBuildingRoad)
{
// Update road preview
Vector2 currentPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
previewLine.SetPosition(1, currentPoint);
}
}
private void CreateRoad(Vector2 start, Vector2 end)
{
// Calculate road position
Vector2 roadPosition = start;
// Calculate road size and rotation
float roadSize = Vector2.Distance(start, end);
float roadRotation = Mathf.Atan2(end.y - start.y, end.x - start.x) * Mathf.Rad2Deg;
// Instantiate the road game object
GameObject road = Instantiate(roadPrefab, roadPosition, Quaternion.Euler(0f, 0f, roadRotation));
road.transform.localScale = new Vector3(roadSize, 1f, 1f);
}
}
答案1
得分: 1
-
将每单位像素更改为32,以便在世界中边长变为1。
-
打开精灵编辑器,将自定义枢轴更改为
X:0 Y:0.5
(精灵的中间左侧)。
英文:
To achieve the same effect, you need to do two more things in the sprite import settings
-
Change Pixels Per Unit to 32, so that the edge length of the sprite becomes 1 in the world.
-
Open the Sprite Editor, change Custom Pivot to
X:0 Y:0.5
(the middle-left of the sprite)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论