【发布时间】:2019-01-29 16:57:03
【问题描述】:
/*我正在 Unity 中制作一个 2d 游戏,其工作方式类似于台球,但还有其他方面。当玩家按住按钮 0 时,一条线会拖离球,以显示球将被击出的方向和速度。我不知道如何设置该速度或如何添加这样的力。
我尝试直接设置速度,然后添加假摩擦,但效果不太好。我还尝试向球添加一个力,并制作一个空的游戏对象,用一个点效应器跟随指针来击退球。但我似乎无法得到任何工作。 --另外我为混乱的代码道歉,我对此还是有点陌生 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineDrawer : MonoBehaviour
{
public Transform tr; //this is the transform and rigid body 2d of the
ball
public Rigidbody2D rb;
public LineRenderer line; // the line rendered is on the ball
public float hitForce = 10;
// Start is called before the first frame update
void Start()
{
line = GetComponent<LineRenderer>();
line.SetColors(Color.black, Color.white);
}
// Update is called once per frame
void FixedUpdate()
{
line.SetPosition(0, tr.position - new Vector3(0, 0, 0));
if (Input.GetMouseButton(0)&&PlayerPrefs.GetInt("Moving")==0)
{
line.SetWidth(.25f, .25f);
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
float len = Vector2.Distance(line.GetPosition(0), line.GetPosition(1)); //this is for determining the power of the hit
}
else
{
line.SetWidth(0, 0); //make the line invisible
}
if (Input.GetMouseButtonUp(0) && (PlayerPrefs.GetInt("Moving")==0))
{
Vector2.Distance(Input.mousePosition, tr.position)*100;
Debug.Log("Up");
rb.velocity = //this is what i cant work out
PlayerPrefs.SetInt("Moving", 1);
}
}
}
//底部5行是我设置速度的地方。
【问题讨论】:
-
顺便说一下,
Update会像您的评论状态那样被调用一次,但FixedUpdate不会。它在物理刻度上运行,无论计算速度有多快。我将通过Update检索输入,但在FixedUpdate中应用基于物理的更改 -
@Eliasar ok thx
-
"我试过直接设置速度,然后添加假摩擦力,但效果不太好。" 具体是什么不起作用?方向正确吗?假摩擦是什么意思?
-
@Foggzie 通过假摩擦我的意思是通过代码减去一点速度,而不是使用物理材料。我遇到的最大问题是如何在释放鼠标时让球向某个方向移动。我不知道是否应该使用 rb.addForce 或使用 rb.velocity = 或使用点效应器
-
@camocStudios_Hagger 好吧,如果您的线渲染器看起来正确,这意味着您已经获得了正确的方向矢量,可以在线的第一个点和第二个点之间使用。
rb.AddForce和rb.velocity =都应该适用于你想做的事情。