Hi all. I need help with some C# scripts I am trying to solve.
(1) I want to move an object left and right on a 2D plane, restricting it within the parameters I will be setting on the inspector.
This is what I've written.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movingObject : MonoBehaviour {
public Vector3 rightEdge;
public Vector3 leftEdge;
public Vector3 currentPosition;
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Vector3.Distance (currentPosition, rightEdge) <= 0) {
transform.position += Vector3.left * speed * Time.deltaTime;
} else if (Vector3.Distance (currentPosition, leftEdge) >= 0) {
transform.position += Vector3.right * speed * Time.deltaTime;
}
}
}
I understand that there is some logic problem here. What if movingObject is at 0?
How can I rectify this problem?
(2) Why does "transform.position" not work on instantiate?
For example:
if (Input.GetKey (KeyCode.Space))
{
GameObject beam = Instantiate (projectilesPrefab, new Vector3 (transform.position.x, -3.5f, transform.position.y), Quaternion.identity) as GameObject;
transform,position += Vector3.up * speed * Time.deltaTime;
}
This code does not work at all. After some googling, I realised I need to use rigidbody2d to get what I want.
I am just curious why does "transform position" not work on an Instantiate statement.
(3) Also with regards to instantiate, similar to script on (2) above. How do I script the rate of instantiate? is there such a thing?
What I mean is, for example, I want instantiate to return every 5 seconds, instead of every frame. How do I go about doing that?
Thank you so much everyone!