转换拖动运动

时间:2015-09-24 21:44:37

标签: c# unity3d transform

所以这就是视频形式的问题

https://pbs.twimg.com/tweet_video/CPsvjgbWoAACKCp.mp4

当没有移动船时,盾牌移动得很好,但是当你开始移动时,它只能拖到你后面移动一点,这根本就不好。我无法弄清楚我在这里做错了什么!

public class ShieldMovement : MonoBehaviour {

public Transform target; //player shield is attaced to
public float circSpeed = 0.1f; // Speed Shield moves around ship

private Vector3 direction = Vector3.up;
private float distance = 0.8f; // distance from player so it doesn't clip
private float deadzone = 0.15f;
private float separation;
private bool canMove = true;

private Vector3 shipPos;

private Rigidbody2D tRB;
private Rigidbody2D rb;

// Use this for initialization
void Start () 
{
    tRB = target.GetComponent<Rigidbody2D>();
    rb = GetComponent<Rigidbody2D>();
}

void OnCollisionEnter2D (Collision2D other) 
{
    canMove = false;
}

void OnCollisionStay2d(Collision2D other)
{
    canMove = false;
}

void OnCollisionExit2D (Collision2D other) 
{
    canMove = true;
}

// Update is called once per frame
void Update () {

    float rh = Input.GetAxisRaw("rightH");
    float rv = Input.GetAxisRaw("rightV");

    shipPos = target.position;

    separation = Mathf.Abs((transform.position - shipPos).magnitude);

    if(Mathf.Abs(rh) > deadzone || Mathf.Abs(rv) > deadzone)
    {
        Vector3 targetDir = new Vector3(rh, rv, 0.0f);
        direction  = Vector3.Slerp(transform.position-shipPos, targetDir, circSpeed);

    }

    Ray ray = new Ray(shipPos, direction); // cast ray in direction of point on circle shield is to go

    if(canMove)
    {
        transform.position = ray.GetPoint(distance); //move shield to the ray as far as the distance
    }

    if(separation != distance) //If the shield get torn away from the ship
    {
        transform.position = ray.GetPoint(distance); //move shield to the ray as far as the distance
    }

    float angleY = transform.position.y - shipPos.y;
    float angleX = -(transform.position.x - shipPos.x);

    float angle = Mathf.Atan2 (angleY, angleX) * Mathf.Rad2Deg-90; //Get angle

    if(Mathf.Abs(rh) > deadzone || Mathf.Abs(rv) > deadzone)
    {
        transform.rotation = Quaternion.AngleAxis(angle,Vector3.forward*-1); // keep shield facing outwards in respect to player
    }


}

void FixedUpdate ()
{
    if(!canMove)
    {

        tRB.velocity = new Vector2(0.0f, 0.0f);
        rb.velocity = new Vector2(0.0f, 0.0f);

    }
}

万分感谢您的帮助:)

2 个答案:

答案 0 :(得分:0)

你需要将盾牌与船一起移动。您可以通过将船速添加到防护罩来实现此目的。 类似的东西:

shipPos = target.position;
transform.position += shipVelocity;
separation = Mathf.Abs((transform.position - shipPos).magnitude);

或者将盾牌作为船舶的儿童对象。

答案 1 :(得分:0)

好的,所以我需要做的就是让盾牌成为一个孩子并摆脱transform.rotation周围的条件陈述,这样它就不会继承父旋转并破坏盾牌。这是小事!