How to move gameobjects from side to side? - c#

using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour {
private int SphereCount = 20;
private float SphereSize = 10.0f;
private Vector3 pos1 = new Vector3(-4,0,0);
private Vector3 pos2 = new Vector3(4,0,0);
public float speed = 5.0f;
// Use this for initialization
void Start () {
var withTag = GameObject.FindWithTag("Terrain");
if (withTag == null)
throw new InvalidOperationException("Terrain not found");
for (var i = 0; i < SphereCount; i++) {
var o = GameObject.CreatePrimitive (PrimitiveType.Sphere);
o.tag = "Sphere";
o.transform.localScale = new Vector3 (SphereSize, SphereSize, SphereSize);
o.transform.position = new Vector3 (i + 20, 1, 1);
}
}
// Update is called once per frame
void Update () {
/*foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]) {
if (go.name == "Sphere") {
go.transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong (Time.time * speed, 1.0f));
}
}*/
}
}
The first thing I can't figure out is how to create the Spheres on the Terrain in more spread area with spaces between each Sphere? It's making them in specific place in a row one near the other one.
The second part is in the Update function if I will use this code I will see only one Sphere and it will move from side to side but only one. All the rest of the Spheres are gone.

Related

How to utilize stacking blocks under the player object(cylinder) by using rigidbodies in unity3d?

I am working on a hypercasual game project which is very similar to Matching Cubes. Initially, I was using transform to stack blocks under my cylinder(player object). But in the game there will be a ramp to jump through it and by using transform I was ignoring the physics and it passes through the ramp. So I changed it a little bit by utilizing the rigidbody for the cylinder. If there is no block it jumps through the ramp but I need it to jump with blocks. The problem is I couldn't find a way to stack them under the cylinder by using rigidbody. Tried MovePosition or AddForce but it does not work at all.
How can I stack the blocks under the cylinder but also make them jump through the ramp together?
Here is my StackManager.cs . There is a Regulator function that will check the 'picks' list and regulate the positions. It is the function where I handle all positioning.
I also tried making the positioning by transform and when it collides with ramp, stop the Regulator() and AddForce(Vector3.up*offset) but it did not move up a bit.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
public class StackManager : MonoBehaviour
{
public static StackManager instance;
[SerializeField] private float distanceBetweenObjs;
[SerializeField] private Transform prevObject = null;
[SerializeField] private Transform parent;
[SerializeField] private Transform cylinder;
[SerializeField] private Transform trailer;
private List<Transform> picks; // Use this to order gate and random gate
private Vector3 firstPosition;
private int comboCounter; // fever mode tracker
private Rigidbody rb;
private Transform prev;
private void Awake() {
if(instance == null) {
instance = this;
}
}
void Start()
{
rb = cylinder.gameObject.GetComponent<PlayerController>().rb;
comboCounter = 0;
picks = new List<Transform>();
firstPosition = new Vector3(cylinder.position.x, cylinder.position.y, cylinder.position.z);
}
// Update is called once per frame
void Update()
{
Regulator();
}
void CheckChildren() {
List<Transform> children = new List<Transform>();
foreach (Transform child in picks)
{
children.Add(child);
}
for(int i = 0; i < children.Count - 2; i++) {
if (children[i].isSameMaterial2(children[i+1], children[i+2])) {
comboCounter++;
Destroy(children[i].gameObject);
Destroy(children[i+1].gameObject);
Destroy(children[i+2].gameObject);
picks.Remove(children[i]);
picks.Remove(children[i+1]);
picks.Remove(children[i+2]);
};
}
if(comboCounter == 3) {
SpeedBoost(); //fever mode
comboCounter = 0;
}
}
public void PickUp(GameObject pickedObj){
pickedObj.tag = "Picked";
pickedObj.transform.parent = parent;
picks.Add(pickedObj.transform);
}
private void Regulator(){
//Position of cylinder
//set y value based on the # of children objects
/**
*hold the first position of cylinder
*make calculation by referencing it
*reference + localScale.y + 0.1f:
*/
Vector3 newPos = new Vector3(cylinder.position.x, firstPosition.y, cylinder.position.z);
foreach (Transform child in picks)
{
newPos.y += child.localScale.y + 0.1f;
}
//cylinder.position = newPos;
rb.MovePosition(newPos);
//Position of children
if(picks.Count>0) {
prevObject = picks[picks.Count-1];
}
/**
*For each child
* cylinder-0.1f-pick-0.1f-pick-...
*/
prev = cylinder;
for(int i = 0; i < picks.Count; i++)
{
if(i==0){
picks[i].position = new Vector3(prev.position.x, prev.position.y-1.2f, prev.position.z);
//picks[i].gameObject.GetComponent<Rigidbody>().position(new Vector3(prev.position.x, prev.position.y-1.2f, prev.position.z));
} else {
//picks[i].gameObject.GetComponent<Rigidbody>().MovePosition(new Vector3(prev.position.x, prev.position.y-prev.localScale.y -0.1f, prev.position.z));
picks[i].position = new Vector3(prev.position.x, prev.position.y-prev.localScale.y -0.1f, prev.position.z);
}
prev = picks[i];
}
//Position of trailer object
if(picks.Count>0) {
trailer.position = new Vector3(prev.position.x, prev.position.y-0.2f, prev.position.z); //relocate the trailer object under last pick
trailer.GetComponent<TrailRenderer>().material = prev.GetComponent<MeshRenderer>().material; //change the color of the trail
}
CheckChildren(); //check for the 3-conjugate combo
}
public void ChangeRampState() {
Debug.Log("prev.gameObject");
Debug.Log(prev.gameObject);
prev.gameObject.GetComponent<Collider>().isTrigger = false;
rb.AddForce(Vector3.up * 300);
}
public void OrderPicks() {
picks.Sort((x, y) => string.Compare(x.GetComponent<MeshRenderer>().sharedMaterial.name, y.GetComponent<MeshRenderer>().sharedMaterial.name));
}
public void ShufflePicks() {
picks = picks.Fisher_Yates_CardDeck_Shuffle();
}
async public void onObstacle(Transform pickToDestroy) {
pickToDestroy.gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
pickToDestroy.parent = null;
await Task.Delay(200);
picks.Remove(pickToDestroy);
}
public void SpeedBoost() {
cylinder.gameObject.GetComponent<PlayerController>().rb.velocity *= 2;
}
}

Trying to get fish to face direction it's moving

So far I'm making an app, and the early stages of it will just be a fish swimming around a small box. I made code that alters the fishes direction randomly and if it reaches certain x or y values to keep it within visibility of the camera. Unfortunately my C# knowledge is limited and I can't figure out how to make it turn the direction it is , this is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishBehavior : MonoBehaviour {
public float speed = 2f;
float moveSpeed = 0f;
private Rigidbody2D rigid;
public float rotateSpeed = 2f;
public bool isPredator = false;
void Start () {
rigid = GetComponent<Rigidbody2D>();
rigid.velocity = new Vector2(speed, 0);
InvokeRepeating("FishMovement", 3f, Random.Range(2f,6f));
}
// Update is called once per frame
void Update () {
int num = Random.Range(1, 10);
if (transform.position.x >= 11.5)
{
speed = -2;
rigid.velocity = new Vector2(speed, 0);
}
if (transform.position.x <= -11.5)
{
speed = 2;
rigid.velocity = new Vector2(speed, 0);
}
if (transform.position.y >= 5.07)
{
rigid.velocity = new Vector2(Random.Range(-2, 2), -2);
}
if (transform.position.y <= -4.65)
{
rigid.velocity = new Vector2(Random.Range(-2, 2), 2);
}
}
void FishMovement()
{
int fishSpeed = Random.Range(-3, 3);
if (fishSpeed != 0)
{
moveSpeed = Random.Range(-2, 2);
rigid.velocity = new Vector2(fishSpeed, moveSpeed);
}
}
}
Anything helps thanks

Why after the spaceships collide with the box collider they are not turning back?

I want that when there is a collider turn the spaceship/s back. But they keep moving forward and out of the box collider and terrain.
The script that make the clones ships that i want to turn back when they collide:
using System;
using UnityEngine;
using Random = UnityEngine.Random;
using System.Collections;
using System.Collections.Generic;
public class SphereBuilder : MonoBehaviour
{
public GameObject SpaceShip;
GameObject[] spheres;
public float moveSpeed = 50;
// for tracking properties change
private Vector3 _extents;
private int _sphereCount;
private float _sphereSize;
/// <summary>
/// How far to place spheres randomly.
/// </summary>
public Vector3 Extents;
/// <summary>
/// How many spheres wanted.
/// </summary>
public int SphereCount;
public float SphereSize;
private void Start()
{
spheres = GameObject.FindGameObjectsWithTag("MySphere");
}
private void OnValidate()
{
// prevent wrong values to be entered
Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
SphereCount = Mathf.Max(0, SphereCount);
SphereSize = Mathf.Max(0.0f, SphereSize);
}
private void Reset()
{
Extents = new Vector3(250.0f, 20.0f, 250.0f);
SphereCount = 100;
SphereSize = 20.0f;
}
private void Update()
{
UpdateSpheres();
MoveShips ();
//lastPosition = child.position;
}
private void MoveShips()
{
foreach (Transform child in spheres[0].transform)
{
child.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
}
}
private void UpdateSpheres()
{
if (Extents == _extents && SphereCount == _sphereCount && Mathf.Approximately(SphereSize, _sphereSize))
return;
// cleanup
var spheres = GameObject.FindGameObjectsWithTag("Sphere");
foreach (var t in spheres)
{
if (Application.isEditor)
{
DestroyImmediate(t);
}
else
{
Destroy(t);
}
}
var withTag = GameObject.FindWithTag("Terrain");
if (withTag == null)
throw new InvalidOperationException("Terrain not found");
for (var i = 0; i < SphereCount; i++)
{
var o = Instantiate(SpaceShip);
o.tag = "Sphere";
o.transform.SetParent(gameObject.transform);
o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);
// get random position
var x = Random.Range(-Extents.x, Extents.x);
var y = Extents.y; // sphere altitude relative to terrain below
var z = Random.Range(-Extents.z, Extents.z);
// now send a ray down terrain to adjust Y according terrain below
var height = 10000.0f; // should be higher than highest terrain altitude
var origin = new Vector3(x, height, z);
var ray = new Ray(origin, Vector3.down);
RaycastHit hit;
var maxDistance = 20000.0f;
var nameToLayer = LayerMask.NameToLayer("Terrain");
var layerMask = 1 << nameToLayer;
if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
{
var distance = hit.distance;
y = height - distance + y; // adjust
}
else
{
Debug.LogWarning("Terrain not hit, using default height !");
}
// place !
o.transform.position = new Vector3(x, y, z);
}
_extents = Extents;
_sphereCount = SphereCount;
_sphereSize = SphereSize;
}
}
And the script of the colliding with the function OnTriggerExit:
using UnityEngine;
using System.Collections;
public class InvisibleWalls : MonoBehaviour {
public float smooth = 1f;
private Vector3 targetAngles;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Sphere")
{
targetAngles = other.transform.eulerAngles + 180f * Vector3.up;
other.transform.eulerAngles = Vector3.Lerp (other.transform.eulerAngles, targetAngles, smooth * Time.deltaTime);
}
}
}
It does get to the two lines:
targetAngles = other.transform.eulerAngles + 180f * Vector3.up;
other.transform.eulerAngles = Vector3.Lerp (other.transform.eulerAngles, targetAngles, smooth * Time.deltaTime);
But they never turn back.
The script that create the cloned ships is attached to a GameObject name Spheres and tagged as MySphere.
The second script is attached to a GameObject called Invisible Walls and that i added to it a box collider with the Is Trigger set to on(checked). And also added to it a Rigidbody and Use Gravity is checked on.
It's because your Lerp method is only called once in OnTriggerExit. Lerp is usually used over time e.g. in Update or a coroutine. Here's how to do it in a coroutine:
void OnTriggerExit(Collider other)
{
if (other.tag == "Sphere")
{
targetAngles = other.transform.eulerAngles + 180f * Vector3.up;
StartCoroutine(TurnShip(other.transform, other.transform.eulerAngles, targetAngles, smooth))
}
}
IEnumerator TurnShip(Transform ship, Vector3 startAngle, Vector3 endAngle, float smooth)
{
float lerpSpeed = 0;
while(lerpSpeed < 1)
{
ship.eulerAngles = Vector3.Lerp(startAngle, endAngle, lerpSpeed);
lerpSpeed += Time.deltaTime * smooth;
yield return null;
}
}

How can i move all the Spheres on the Terrain from it's original positions to new positions and back to the original in a loop?

What i want it to do is both in the editor and when running the game to see all the Spheres in the same time moving to another direction or maybe it will be the same direction untill endPoint and then back to the startPoint in a loop none stop.
This is my script:
using System;
using UnityEngine;
using Random = UnityEngine.Random;
[ExecuteInEditMode]
public class SphereBuilder : MonoBehaviour
{
// for tracking properties change
private Vector3 _extents;
private int _sphereCount;
private float _sphereSize;
/// <summary>
/// How far to place spheres randomly.
/// </summary>
public Vector3 Extents;
/// <summary>
/// How many spheres wanted.
/// </summary>
public int SphereCount;
public float SphereSize;
private void OnValidate()
{
// prevent wrong values to be entered
Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
SphereCount = Mathf.Max(0, SphereCount);
SphereSize = Mathf.Max(0.0f, SphereSize);
}
private void Reset()
{
Extents = new Vector3(250.0f, 20.0f, 250.0f);
SphereCount = 100;
SphereSize = 20.0f;
}
private void Update()
{
UpdateSpheres();
}
private void UpdateSpheres()
{
if (Extents == _extents && SphereCount == _sphereCount && Mathf.Approximately(SphereSize, _sphereSize))
return;
// cleanup
var spheres = GameObject.FindGameObjectsWithTag("Sphere");
foreach (var t in spheres)
{
if (Application.isEditor)
{
DestroyImmediate (t);
}
else
{
Destroy(t);
}
}
var withTag = GameObject.FindWithTag("Terrain");
if (withTag == null)
throw new InvalidOperationException("Terrain not found");
for (var i = 0; i < SphereCount; i++)
{
var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
o.tag = "Sphere";
o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);
// get random position
var x = Random.Range(-Extents.x, Extents.x);
var y = Extents.y; // sphere altitude relative to terrain below
var z = Random.Range(-Extents.z, Extents.z);
// now send a ray down terrain to adjust Y according terrain below
var height = 10000.0f; // should be higher than highest terrain altitude
var origin = new Vector3(x, height, z);
var ray = new Ray(origin, Vector3.down);
RaycastHit hit;
var maxDistance = 20000.0f;
var nameToLayer = LayerMask.NameToLayer("Terrain");
var layerMask = 1 << nameToLayer;
if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
{
var distance = hit.distance;
y = height - distance + y; // adjust
}
else
{
Debug.LogWarning("Terrain not hit, using default height !");
}
// place !
o.transform.position = new Vector3(x, y, z);
}
_extents = Extents;
_sphereCount = SphereCount;
_sphereSize = SphereSize;
}
}
Update
I created another c# script and dragged it to the Terrain.
using UnityEngine;
using System.Collections;
public class MoveSpheres : MonoBehaviour {
public Transform _transform;
private Vector3 pos1 = new Vector3(-4,0,0);
private Vector3 pos2 = new Vector3(4,0,0);
public float speed = 1.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
_transform.position = Vector3.Lerp (pos1, pos2, Mathf.PingPong(Time.time*speed, 1.0f));
}
}
This script move one Sphere. But i want to move all the Spheres.
And also if i change in the first script the number of Spheres then move them too keep move them too.
The problem is with the Destroy part in the first script.
you can lerp the spheres from one position to another and back https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Create shapes in android with unity

I am trying to create custom shapes in unity with free hand but i am getting very thick shapes Like this
I am using this code
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class DrawLine : MonoBehaviour
{
public Text toshow;
private LineRenderer line;
private bool isMousePressed;
public List<Vector3> pointsList;
private Vector3 mousePos;
// Structure for line points
struct myLine
{
public Vector3 StartPoint;
public Vector3 EndPoint;
};
// -----------------------------------
void Awake ()
{
// Create line renderer component and set its property
line = gameObject.AddComponent<LineRenderer> ();
line.material = new Material (Shader.Find ("Particles/Additive"));
line.SetVertexCount (0);
line.SetWidth (0.1f, 0.1f);
line.SetColors (Color.green, Color.green);
line.useWorldSpace = true;
isMousePressed = false;
pointsList = new List<Vector3> ();
// renderer.material.SetTextureOffset(
}
// Following method adds collider to created line
private void addColliderToLine(Vector3 startPos, Vector3 endPos)
{
BoxCollider col = new GameObject("Collider").AddComponent<BoxCollider> ();
col.gameObject.tag = "Box";
col.transform.parent = line.transform; // Collider is added as child object of line
float lineLength = Vector3.Distance (startPos, endPos); // length of line
col.size = new Vector3 (lineLength, 0.1f, 1f); // size of collider is set where X is length of line, Y is width of line, Z will be set as per requirement
Vector3 midPoint = (startPos + endPos)/2;
col.transform.position = midPoint; // setting position of collider object
// Following lines calculate the angle between startPos and endPos
float angle = (Mathf.Abs (startPos.y - endPos.y) / Mathf.Abs (startPos.x - endPos.x));
if((startPos.y<endPos.y && startPos.x>endPos.x) || (endPos.y<startPos.y && endPos.x>startPos.x))
{
angle*=-1;
}
angle = Mathf.Rad2Deg * Mathf.Atan (angle);
col.transform.Rotate (0, 0, angle);
}
void createCollider(){
for (int i=0; i < pointsList.Count - 1; i++) {
addColliderToLine(pointsList[i],pointsList[i+1]);
}
}
public void MouseDrag(){
#if UNITY_ANDROID
Vector2 touchPos = Input.touches[0].position;
mousePos = Camera.main.ScreenToWorldPoint (new Vector3(touchPos.x, touchPos.y, 0));
mousePos.z = 0;
if (!pointsList.Contains (mousePos)) {
pointsList.Add (mousePos);
line.SetVertexCount (pointsList.Count);
line.SetPosition (pointsList.Count - 1, (Vector3)pointsList [pointsList.Count - 1]);
}
#endif
}
public void MouseBeginDrag(){
isMousePressed = true;
line.SetVertexCount (0);
GameObject[] ob = GameObject.FindGameObjectsWithTag("Box");
for(int i=0; i<ob.Length; i++){
Destroy(ob[i]);
}
pointsList.RemoveRange (0, pointsList.Count);
line.SetColors (Color.green, Color.green);
}
public void MouseFinishDrag(){
createCollider();
isMousePressed = false;
}
// -----------------------------------
void Update ()
{
}
}
Please Help me to decrease the width of a line. I am not able to decrease the width of a line. Please help me

Categories