简体   繁体   English

Unity3D-通过单击将对象向相反方向移动

[英]Unity3D - Move an object to the opposite direction by clicking on it

I'm new in Unity and I'm working on a simple project but I'm stuck. 我是Unity的新手,正在从事一个简单的项目,但遇到了麻烦。

So my idea is when the player touches the bottom side of a ball it goes the opposite direction. 所以我的想法是,当玩家触碰到球的底部时,它会朝相反的方向运动。 Pretty much like in real life, if you kick a ball on the bottom side it will go up, but in 2D version. 就像在现实生活中一样,如果您在底侧踢球,球将会上升,但是在2D版本中。

I tried finding the opposite point of where the player touched the ball and making a vector by subtracting the original point and the opposite point, and then applying force to move the ball but it doesn't work. 我尝试找到玩家接触球的相反点,并通过减去原始点和相反点,然后施加力来移动球,但制作了一个矢量,但这是行不通的。

void MoveBall()
{
     x = mouseClickPosition.x;
     y = mouseClickPosition.y;
     oppositeClickPosition.x = -x;
     oppositeClickPosition.y = -y;
     Vector2 direction = oppositeClickPosition - mouseClickPosition;
     rb.AddForce(direction * force, ForceMode.Impulse);
}

You have to subtract the mousePosition and the center of the ball. 您必须减去mousePosition和球的中心。

Vector3 clickedPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 ballCenter = ballTransform.position;

// If this goes the opposite direction just swap the values.
Vector3 forceDirection = (ballCenter  - clickedPosition).normalized;

ballRigidbody.AddForce (forceDirection * strength, ForceMode.Impulse);

This way you find the direction and add the force you want, you can not use the normalized Vector3 if you want to use the distance as a factor too. 这样,您可以找到方向并添加所需的力,如果您也要使用距离作为因数,则不能使用normalized Vector3。

And you can catch that event properly on OnMouseDown if the ball has a collider 如果球有对撞机,则可以在OnMouseDown上正确捕获该事件

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

This may be helpful: https://answers.unity.com/questions/681698/vector-between-two-objects.html It Explains how to do it in 3D but the idea applies to both. 这可能会有所帮助: https : //answers.unity.com/questions/681698/vector-between-two-objects.html它说明了如何在3D模式下进行操作,但这种想法对两者都适用。

In your case, instead of oppositeClickPosition you should use the position of the ball: 在您的情况下,应该使用球的位置,而不是相反的ClickPosition:

Vector2 direction = transform.position - mouseClickPosition; Vector2方向= transform.position-mouseClickPosition;

(replace transform.position with the position of the ball if this script is not attatched to the ball) (如果此脚本未附加到球上,请用球的位置替换transform.position)

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM