/*I正在用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行是我设置速度的位置。
发布于 2019-01-30 02:24:33
只需将您的脚本重写为以下代码:
using UnityEngine;
public class Ball : MonoBehaviour
{
private LineRenderer line;
private Rigidbody2D rb;
void Start()
{
line = GetComponent<LineRenderer>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
line.SetPosition(0, transform.position);
if (Input.GetMouseButton(0))
{
line.startWidth = .05f;
line.endWidth = .05f;
line.SetPosition(1, Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
else
{
line.startWidth = 0;
line.endWidth = 0;
}
if (Input.GetMouseButtonUp(0))
{
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
direction.Normalize();
rb.AddForce(direction * 3f, ForceMode2D.Impulse);
}
}
}
https://stackoverflow.com/questions/54426035
复制相似问题