My second cube won't run - c#

In my game one normal cube change to a smaler cube.
using UnityEngine;
public class PlayerSkift : MonoBehaviour {
public GameObject myObject1;
public GameObject myObject2;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow))
{
myObject1.SetActive (false);
myObject2.SetActive (true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
myObject2.SetActive(false);
myObject1.SetActive(true);
}
}
}
This code is whats make it do so.
But when i change to my small cube, it won't go anywhere. This scrip makes the cube run.
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
Its on the smaller cube. So the smaller cube follows the bigger, this code:
using UnityEngine;
public class Pl2føglPl1 : MonoBehaviour
{
public Transform player1;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
transform.position = player1.position + offset;
}
}
when the bigger cube disappear, the little one won't start running. Pleas help if you can.

Here's what happens:
public class PlayerMovement
makes normal cube move. But public class PlayerSkift does myObject1.SetActive (false); so normal cube gets deactivated. And it doesn't get void FixedUpdate () event handler fired up anymore. So normal cube doesn't go anywhere, so smaller cube, following it, doesn't go anywhere either.
You need to create some "dummy" invisible GameObject, make your cubes children of if, attach public class PlayerMovement to it, so it always moves, regardless of inner children cubes states. And both children cubes will of course follow their parent's coordinates, since they are positioned relatively to parent. So you only move parent, and no need to synchronize cubes one to another, so you don't need public class Pl2føglPl1 at all.

This is the code i ended up using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSkiftStørelse : MonoBehaviour {
public Vector3 small;
public Vector3 normal;
public Vector3 high;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.DownArrow)) //getkeydown??
{
transform.localScale = small;
}
if (Input.GetKeyDown (KeyCode.UpArrow)) //getkeydown??
{
transform.localScale = normal;
}
}
}

Related

Firing Projectiles in Unity

Im trying to build a weapon in a game using Unity. My bullets spawn but i cant seem to get the force to apply on instantiation to get them to actually fire.
My weapon script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public Rigidbody2D projectile;
public float forceMultiplier;
public Vector2 direction;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
public void Fire(float force, Vector2 direction)
{
Instantiate(projectile, firePoint.position, transform.rotation);
projectile.AddForce(direction * force);
}
// Update is called once per frame
void Update () {
if (timeBtwShots <= 0)
{
if (Input.GetKeyDown(KeyCode.Return))
{
Fire(forceMultiplier, direction);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
You need to add the force to the spawned object and not the prefab.
Your code should be something like this:
public void Fire(float force, Vector2 direction)
{
Rigidbody2D proj = Instantiate(projectile, firePoint.position, transform.rotation);
proj.AddForce(direction * force);
}

Unity prefab movement

Hello i want to create a group of the same prefab following the player in my game. I already got the prefab intantiation to follow the player but when there is more than one they just follow the exact same path on top of each other. is there a way where they can follow the player but act like a bunch of bees moving?
Thanks!
This is the script on my prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillerMovement : MonoBehaviour {
public GameObject player;
void FixedUpdate()
{
Vector2 toTarget = player.transform.position - transform.position;
float speed = 0.5f;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
The best solution depends on you game logic, but you may consider having a delay before starting following (you can tweak the delay depending on the position you want to the particular object to assume in the trail.
using System.Collections;
using UnityEngine;
public class Follower : MonoBehaviour
{
public GameObject player;
public float delay = 0f;
public float speed = .5f;
bool isReady = false;
void Start()
{
StartFollowing();
}
public void StartFollowing()
{
StartCoroutine(WaitThenFollow(delay));
}
IEnumerator WaitThenFollow(float delay)
{
yield return new WaitForSeconds(delay);
isReady = true;
Debug.Log(gameObject.name);
Debug.Log(Time.time);
}
void FixedUpdate()
{
if (isReady && player != null)
{
Vector2 toTarget = player.transform.position - transform.position;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
}
I've called StartFollowing in the Start method for you to test the code. You should call this method whenever approrpiate in your game logic.

Wheel Mesh Not rotating with Wheel Collider

So I'm working on a racing game but first need to get my wheel collider and wheel mesh functioning properly but for some reason they don't appear to be in sync. The wheel colliders rotate for steering and for acceleration but the wheel mesh does not follow, instead it stays idle when testing.
This is the code I have used to get the vehicle moving and wheel colliders spinning which is supposedly meant to make the wheel mesh spin also.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleCougarInfo {
public WheelCollider LeftWheel;
public GameObject LeftWheelMesh;
public WheelCollider RightWheel;
public GameObject RightWheelMesh;
public bool motor;
public bool steering;
}
public class CougarController : MonoBehaviour {
public List<AxleCougarInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;
public void ApplyLocalPositionToVisual(AxleCougarInfo wheelPair)
{
wheelPair.LeftWheelMesh.transform.Rotate (Vector3.left, Time.deltaTime * wheelPair.LeftWheel.rpm * 10, Space.Self);
wheelPair.RightWheelMesh.transform.Rotate (Vector3.right, Time.deltaTime * wheelPair.RightWheel.rpm * 10, Space.Self);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void FixedUpdate() {
float motor = maxMotorTorque * Input.GetAxis ("Horizontal");
float steering = maxSteeringAngle * Input.GetAxis ("Vertical");
foreach (AxleCougarInfo axleInfo in axleInfos)
{
if (axleInfo.steering == true)
{
axleInfo.LeftWheel.steerAngle = steering;
axleInfo.RightWheel.steerAngle = steering;
}
if (axleInfo.motor == true)
{
axleInfo.LeftWheel.motorTorque = motor;
axleInfo.RightWheel.motorTorque = motor;
}
}
}
}

unity3D, enemy following issue

I'm trying to make enemies follow my player when the player enters the radius area of an enemy, but make the enemy stop following when my bullet hits object or enters radiusArea.
See my gif for more detail:
Gif
script:
using UnityEngine;
using System.Collections;
public class FlyEnemyMove : MonoBehaviour
{
public float moveSpeed;
public float playerRange;
public LayerMask playerLayer;
public bool playerInRange;
PlayerController thePlayer;
// Use this for initialization
void Start()
{
thePlayer = FindObjectOfType<PlayerController>();
}
// Update is called once per frame
void Update()
{
flip();
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, moveSpeed * Time.deltaTime);
//Debug.Log(transform.position.y);
}
//Debug.Log(playerInRange);
}
void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, playerRange);
}
void flip()
{
if (thePlayer.transform.position.x < transform.position.x)
{
transform.localScale = new Vector3(0.2377247f, 0.2377247f, 0.2377247f);
}
else
{
transform.localScale = new Vector3(-0.2377247f, 0.2377247f, 0.2377247f);
}
}
}
I hope someone can help me :(
Physics2D.OverlapCircle detects only the collider with the lowest z value (if multiple are in range). So you either need to change the z values so the player has the lowest or you need to work with Physics2D.OverlapCircleAll and check the list to find the player. Or you could change your layers so only the player itself is on that specific layer you feed into the overlap test.

Give every prefab his own speed

Is was building a star background simulation for a spaceshooter game in UNITY3D.
In c# i built The Instantitiation of prefabs which look like dots. While the generation of multiple dots on random spots on the x-axis go perfectly i wanted to add one thing.
Random speed. The problem is that i don't know how to give every prefab his own speed en keep it instead of getting overwritten by the next randomnization.
backgroundloop.cs
using UnityEngine;
using System.Collections;
public class backgroundloop : MonoBehaviour {
public GameObject star;
public float spawnTime;
private GameObject starPrefab;
private float timestamp;
//public float hoogte = Random.Range(-1.01f,1.1f);
//public float rotationPrefab = transform.localEulerAngles.z;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Time.time > timestamp) {
starPrefab = Instantiate
(star, new Vector3(7,Random.Range(-5.0f,5.0f),0),
Quaternion.Euler(0, 0, 0)) as GameObject;
timestamp = Time.time + spawnTime;
}
}
}
And the problem is in this script:
prefabMovement.cs
using UnityEngine;
using System.Collections;
public class prefabMovement : MonoBehaviour {
float speed = Random.Range (-3f, -0.1f);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate (new Vector3(-1f,0,0) * Time.deltaTime);
if (transform.position.x < -6.8) {
Destroy (this.gameObject);
}
}
}
Huh? So the speed is overwritten and eventually ends up being the same on all instantiated prefabs?
Maybe it helps if initialize the speed variable inside the Start method.

Categories