首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将精灵的速度设置为与鼠标指针相反的方向?

如何将精灵的速度设置为与鼠标指针相反的方向?
EN

Stack Overflow用户
提问于 2019-01-30 00:57:03
回答 1查看 63关注 0票数 0

/*I正在用Unity制作一个2d游戏,它的工作原理类似于台球,但与其他方面类似。当球员按住按钮0时,一条线拖离球,以显示球将被击出的方向和速度。我不知道如何设置速度,或者如何添加这样的力。

我试着直接设置速度,然后添加假摩擦,但效果不是很好。我还试着给球增加一个力,并在指针后面做一个空的游戏对象,用一个点效应器来排斥球。但是我似乎不能让任何东西工作。--另外,我为混乱的代码道歉,我对此还是个新手*/

代码语言:javascript
运行
复制
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行是我设置速度的位置。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-30 10:24:33

只需将您的脚本重写为以下代码:

代码语言:javascript
运行
复制
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);       
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54426035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档