- Home /
ping pong on x axis, unable to touch end of plane,
I have a rectangle,
I want to move a red line, from min x to max x and have it move back and forth.
I have the line moving however, I cannot seem to get the max X correct., and the line will stop half way into the parent
any idea what I am doing wrong here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movingplatformscript : MonoBehaviour {
public GameObject child;
public float min;
public float max;
// Use this for initialization
void Start () {
foreach (Transform childObj in transform)
{
min = childObj.gameObject.transform.localPosition.x;
max = childObj.gameObject.GetComponent<Renderer>().bounds.max.x;
child = childObj.gameObject;
}
}
// Update is called once per frame
void Update () {
child.transform.localPosition = new Vector3(Mathf.PingPong(Time.time*2,max-min)+min, child.transform.localPosition.y, child.transform.localPosition.z);
}
}
I'm not sure if this is a problem with PingPong. You're going about this in a pretty weird way...
What is the purpose of iterating over the children in Start? Is there a reason your $$anonymous$$imum is set as current position, but the maximum is the renderer's max bounds?
I used the loops to find the child and store the $$anonymous$$imum because the child object is placed on the $$anonymous$$imum x before it starts moving
localPosition
isn't always intuitive as it seems. Try replacing your localPosition
usages here with just position
.
Answer by rohkgaming · Apr 24, 2018 at 10:50 PM
Script i got this to work with, works with rotation of parents parent, if anyone has any idea on optimisations maybe I can use for this please comment
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movingplatformscript : MonoBehaviour {
public GameObject parent;
public GameObject child;
public float min;
public float max;
// Use this for initialization
void Start () {
parent = gameObject;
parent.SetActive(true);
child = gameObject.transform.GetChild(0).gameObject;
Bounds bounds = gameObject.transform.GetComponent<Renderer>().bounds;
min = gameObject.transform.InverseTransformPoint(bounds.min).x;
max = gameObject.transform.InverseTransformPoint(bounds.max).x;
}
// Update is called once per frame
void Update () {
child.transform.localPosition = new Vector3(Mathf.PingPong(Time.time*2,max-min)+min, child.transform.localPosition.y, child.transform.localPosition.y);
}
}
Your answer
Follow this Question
Related Questions
transform.position not setting position OR animation setting position even though it shouldn't 0 Answers
[2D] Get the position of an object outside the scope 2 Answers
moving objects with transform position 2 Answers
Update instantiates more than 1 object 2 Answers
how can i change the x position while jumping on air using c#? 1 Answer