Hi!
I’m an absolute newbie to unity and I thought I’d ask for help for a problem I’ve been having trouble with.
I’ve been trying to create a line that creates new segments and extends and rotates towards the cursor, but I’m having a little bit of trouble.
I managed to get it working horizontally the way I want it to, but I’m having a bit of trouble to add vertical movement too.
I figured I’d ask for help here because I couldn’t find many answers for other places, and this is where 90% of the answers online came from.
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddNewGameObjects : MonoBehaviour
{
public List<GameObject> newGameObjects = new List<GameObject>();
public Vector2 mousePos = new Vector2();
public float xPos;
public float yPos;
public GameObject newGameObject;
SpriteRenderer spriteRenderer;
public Sprite sprite;
public bool createNewSprite = false;
public int newGameObjectCount;
public bool mouseMoved;
public GameObject parentGameObject;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 2; i++)
{
CreateNewGameObject();
if (i == 0)
{
newGameObjects[i].transform.position = new Vector3(-8, 0, 0);
}
else if (i == 1)
{
newGameObjects[i].transform.position = new Vector3(-3, 0, 0);
}
}
}
// Transform of the object we want to stretch
// Update is called once per frame
void Update()
{
if (Input.GetAxis("Mouse X") != 0)
{
mouseMoved = true;
}
xPos = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
if (newGameObjects[newGameObjects.Count - 1].transform.position.x - newGameObjects[0].transform.position.x > 1)
{
CreateNewGameObject();
}
for (int i = 1; i < newGameObjects.Count; i++)
{
newGameObjects[i].transform.position = (new Vector3(xPos - i - 1, 0, 0));
}
if (newGameObjects[newGameObjects.Count - 1].transform.position.x <= -8 && newGameObjects.Count > 2 && mouseMoved == true)
{
GameObject gameObjectToDestroy = newGameObjects[newGameObjects.Count - 1];
newGameObjects.RemoveAt(newGameObjects.Count - 1);
Destroy(gameObjectToDestroy);
}
mouseMoved = false;
}
public void CreateNewGameObject()
{
newGameObject = new GameObject();
newGameObject.AddComponent<SpriteRenderer>();
spriteRenderer = newGameObject.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = sprite;
newGameObject.transform.localScale = new Vector2(10, 10);
newGameObject.transform.parent = parentGameObject.transform;
newGameObjects.Add(newGameObject);
}
}