0
\$\begingroup\$

coding noob 3D artist here. I'm trying to create a scrolling parallax background with 3D objects, I have it set so that when it scrolls off screen, it resets it's position off screen on the opposite side so it repeats. However, If I want to have multiple depths to these background objects, it needs to not reset that objects position in the Z axis, or when it loops once it'll just overlap the other objects. How can I tell it to ignore the Z axis on resets? Here's what I have so far.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BGSLIDE : MonoBehaviour
{
    public float speed = 2.0f;
    public Transform cube;
    public CC player;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        cube.position += new Vector3(speed*player.velocity.x, 0, 0); 
       if (cube.position.x > 10)
        {
            cube.position = new Vector3(-10,0,0);
        }
       if (cube.position.x < -10)
        {
            cube.position = new Vector3(10,0,0); 
        }


    }

}
\$\endgroup\$
2
  • \$\begingroup\$ It resets Z coordinate to 0, but should preserve its value? \$\endgroup\$ – trollingchar Jul 3 '19 at 14:23
  • \$\begingroup\$ Yes, it should preserve it's Z value. is there a way to store that and carry it over? @trollingchar \$\endgroup\$ – 3D Artist Jul 3 '19 at 14:51
1
\$\begingroup\$

It's simple, you can just read z of that position and pass it as a parameter when creating Vector3 for new position:

void Update () {
    var p = cube.position;
    cube.position = new Vector3 (
        Mathf.Clamp (p.x + speed * player.velocity.x, -10, 10)
        0,
        p.z
    ); 
}

Note the Clamp call. It does the same as your two conditions, but shorter.

\$\endgroup\$
2
  • \$\begingroup\$ Awesome, that works! Thanks! \$\endgroup\$ – 3D Artist Jul 3 '19 at 15:18
  • 1
    \$\begingroup\$ Hey! @3DArtist On stack exchange sites, it's a custom to mark the answer that helped you the most as "accepted" (and to upvote those that were helpful). This helps the system show future visitors what they're most likely looking for. It's totally optional though, so no one is going to be mad if you don't :) More details on the help center. \$\endgroup\$ – Vaillancourt Jul 3 '19 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.