0
votes

I need my PlayerController (which is generated dynamically) to have it's position updated each frame, so it is always centered between the center line and the anchor end: https://goo.gl/G9ZZTp

Here is the code I am using right now:

using UnityEngine; using System.Collections;

public class CenterPlayer : MonoBehaviour {

private GameObject origin;
private GameObject destination;
private GameObject anchor;

// Use this for initialization
void Start () {
    origin = GameObject.Find("Origin");
    Debug.Log(origin);
    destination = GameObject.Find("Destination");
    anchor = GameObject.Find("Left");
}

// Update is called once per frame
void Update () {
    float targetXposition = (((origin.transform.position.x + destination.transform.position.x) / 2f) + anchor.transform.position.x) / 2f;

    Vector3 position = transform.position; 
    this.transform.position = new Vector3(targetXposition, position.y, position.y);
}

I have this script attached to the playerController. It doesn't work and I can't figure out why. The line will move sometimes and I need the player to be always centered between the line and the anchor.

1

1 Answers

0
votes

The problem lies within this line of code:

float targetXposition = (((origin.transform.position.x + destination.transform.position.x) / 2f) + anchor.transform.position.x) / 2f;

What needs to happen is to obtain a direction vector, which is normalized, and then calculate the distance between the origin and destination, then scale the direction vector with half the distance like so:

Vector3 direction = (origin.transform.position + destination.transform.position).normalized;
Vector3 relativePosition = direction * (0.5f * Vector3.Distance(origin.transform.position, destination.transform.position);

This provides a relative position in which adding your anchor point results in the finished calculation of the target position:

float targetXPosition = (anchor.transform.position + relativePosition).x;