2017-09-06 67 views
0

我希望我的对象永远向目标方向移动或直到它碰撞,碰撞部分我已经处理它;但是,我在运动部分遇到问题。翻译对象直到碰撞

我第一次尝试使用的代码

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是rigidbody2D

以及

rb.AddForce(rb.position + f * Time.deltaTime * speed); 

但在这两种情况下,物体旋转,但从来没有移动

我也用翻译和MovePosition的行为相同

P.S.这是一个2D游戏

+0

发布完整的代码,包括更新,碰撞触发等... – Isma

+0

@Isma谢谢你,我可以通过使用直线方程来解决它。我回答了我的问题,如果你想看看这种方法。 –

回答

0

看过网络后,我没有找到任何真正符合我所寻找的内容的东西,您无法永远翻译运动对象(显然,您必须处理该对象应该得到的东西在某个点或某处销毁,但这不是问题)。所以我继续,并决定写我自己的图书馆,以使这个简单。我能够使用直线方程实现我的目标。简单的我采取了这些步骤来解决我的问题。

  1. 在启动我得到2点间的斜率
  2. 计算y截距
  3. 使用具有固定的X值(步骤)的直线方程平移对象,每一个x值找到对应的y值并将对象翻译成它。
  4. 在FixedUpdate中重复步骤3,就是这样。

当然还有更多的情况,处理x = 0的情况,这会给斜坡0或y = 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); 

现在FixedUpdate

//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); 

请记住,这不会做繁重,有很多的条件这需要考虑。