我希望我的对象永远朝目标的方向移动,或者直到碰撞为止,我已经处理过的碰撞部分;但是,我对运动部分有问题。
我首先尝试使用这些代码行旋转目标
Vector2 diff = target - transform.position;
float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0.0f, 0.0f, angle);
这是完美的,我的对象朝我想要的方向旋转。在我的更新方法中,我有以下
if (isMoving)
{
Vector2 f = transform.forward;
transform.position = Vector3.MoveTowards(transform.position, target + Vector3.forward, speed * Time.deltaTime);
}
现在运行但无法实现目标,我知道为什么,这是有道理的,但不确定如何修复它。该对象向正确的方向移动到点,但我不希望它停在目标上,我希望它继续前进。
我也尝试了
rb.MovePosition(rb.position + f * Time.deltaTime * speed);
rb是一个刚性2D
以及
rb.AddForce(rb.position + f * Time.deltaTime * speed);
但是在这两种情况下,对象都旋转但永远不会移动
我也使用了翻译和与MovePosition相同的行为
P.S。这是一个2D游戏
在浏览互联网之后,我找不到任何真正有助于我想要的东西的东西,您无法永远翻译一个运动对象(显然,您必须处理它对象应该在某个时候被摧毁,但这不是问题)。因此,我继续决定写自己的图书馆以简单简单。我能够使用线方程来实现我的目标。简单,我采取了这些步骤来解决我的问题。
- 一开始,我得到2分之间的斜率
- 计算Y截距
- 使用固定x值(步骤)的行方程转换对象(每个x值)找到相应的y值并将对象转换为它。
- 在固定的update中重复步骤3,就是这样。
当然还有更多,处理x = 0的案例将为斜率或y = 0等提供0分部...我在库中解决了所有这些。对于有兴趣的任何人,您可以在此处查看easymovement
如果您不想要库,那么这是一个简单的代码。
//Start by Defining 5 variables
private float slope;
private float yintercept;
private float nextY;
private float nextX;
private float step;
private Vector3 direction; //This is your direction position, can be anything (e.g. a mouse click)
在开始方法
//step can be anything you want, how many steps you want your object to take, I prefer 0.5f
step = 0.5f;
//Calculate Slope => (y1-y2)/(x1-x2)
slope = (gameObject.transform.position.y - direction.y) / (gameObject.transform.position.x - direction.x);
//Calculate Y Intercept => y1-x1*m
yintercept = gameObject.transform.position.y - (gameObject.transform.position.x * slope);
现在在 filexupdate
//Start by calculating the nextX value
//nextX
if (direction.x > 0)
nextX = gameObject.transform.position.x + step;
else
nextX = gameObject.transform.position.x - step;
//Now calcuate nextY by plugging everything into a line equation
nextY = (slope * nextX) + yintercept;
//Finally move your object into the new coordinates
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, new Vector3(nextX, nextY, 0), speed * Time.deltaTime);
请记住,这不会繁重,需要考虑很多条件。