当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Issue with moving object along dynamically defined line

问题描述:

I'm an absolute programming beginner. I'm working on a tiny game prototype just for fun.

You are dragging a character. When you drag the character, the char stays still and you see a targeting line, pointing the opposite direction. When you release the mouse button, the character should move along the targeting line until he hits something.

Everything pretty much works. But there is a slight offset. The character is moving a bit off the targeting line. I feel there is something wrong in the raycast part of the code (in the Dragging() method).

Here is my code:

using UnityEngine;

using System.Collections;

public class PlayerControllerTest : MonoBehaviour {

Rigidbody2D rig;

int dragging;

Vector3 mousePosition;

bool wasMoving;

LineRenderer lineRenderer;

void Start () {

lineRenderer = GetComponent<LineRenderer> ();

rig = GetComponent<Rigidbody2D> ();

}

void Update () {

if (dragging == 1) {

Dragging ();

}

if (dragging == 2) {

float distanceMouseToPlayer = Vector3.Distance (transform.position,mousePosition);

rig.velocity = (-transform.InverseTransformPoint (mousePosition))/distanceMouseToPlayer * 3;

}

}

void OnMouseDown()

{

dragging = 1;

}

void Dragging()

{

mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

mousePosition.z = 0f;

var layerMask = 1 << 8;

layerMask = ~layerMask;

RaycastHit2D hit = Physics2D.Raycast (mousePosition,transform.position- mousePosition,Mathf.Infinity,layerMask);

lineRenderer.enabled = true;

lineRenderer.SetPosition (0, transform.position);

lineRenderer.SetPosition (1, hit.point);

}

void OnMouseUp()

{

dragging = 2;

lineRenderer.enabled = false;

}

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: