My game is a 2D top down platform, I have an zombie enemy that moves up and down the stage, I can place obstacles (such as a create) in its way to stop the enemy, the enemy has the ability to dodge these obstacles at any random moment. If the enemy collided with the create, the enemy will stop its movement to break the create. Once the create is broken, the enemy will continue to moving up, hit point B and then will move back down the stage. My Problem: If the enemy were to dodge left (for example) and then continues to move down and passes another create, the enemy will ignore collision and the function for it to stop and break that create. How do I fix this issue?
public bool hitCollider = false;
public bool hitCollider2 = false;
public bool canMove = true;
public bool moveDown = false;
public bool isMovingUp = true;
public bool isMovingDown = false;
public bool isSomethere = false;
public bool ifMoving;
public float velocidadMax;
public float xMax;
public float xMin;
public float delay;
public float x;
private float tiempo;
public float countDown, countUp, startTime;
void Start () {
Bcol = GetComponent<BoxCollider2D> ();
Bcol.isTrigger = true;
isMovingUp = true;
rigid = GetComponent <Rigidbody2D> ();
velocidadMax = 0.12f;
x = velocidadMax;
InvokeRepeating ("turnFalse", startTime, countDown); // changing lanes
InvokeRepeating ("turnTrue", 0, countUp); // moving up or down
ifMoving = true;
movedownSpeed = -4f;
moveupSpeed = 4f;
hascollidedwHouse = false;
}
void Update () {
if (moveDown == false) {
rigid.velocity = new Vector2 (0, moveupSpeed); // moving up
if (ifMoving == true) {
//irrelevant - don't need to know code here!
} else if (ifMoving == false) {
movedownSpeed = -4;
moveupSpeed = 0;
Move ();
}
}
if (moveDown == true) {
if (hitMascot2 == true) {
} else if (hitMascot2 == false) {
movingDown = true;
Bcol.isTrigger = true;
StartCoroutine (waitMove ());
StartCoroutine (destroyObj ());
}
}
if (isMovingDown == true) {
Debug.Log ("MovingDown");
Bcol.isTrigger = true;
if (canMove == false) {
Debug.Log ("is False" + canMove);
moveupSpeed = 4f;
}
hitCollider = false;
hitCollider2 = false;
}
if (hitCollider == true) {
StartCoroutine (wait ());
Debug.Log ("I HAVE COLLIDED");
if (canMove == true) {
movedownSpeed = 0f;
}
if (canMove == false) {
movedownSpeed = -4f;
}
moveupSpeed = 0f;
}
if (hitCollider2 == true) {
StartCoroutine (wait2 ());
Debug.Log ("I HAVE COLLIDED");
if (canMove == true) {
movedownSpeed = 0f;
}
if (canMove == false) {
movedownSpeed = -4f;
}
moveupSpeed = 0f;
}
}
void OnTriggerEnter2D (Collider2D col) {
if (col.tag == "objects") {
hitCollider = true;
woodBox = true;
canMove = false;
moveDown = false;
xMax = 0;
xMin = 0;
if (hascollidedwHouse == true) {
moveDown = false;
isMovingDown = false;
movedownSpeed = 0;
moveupSpeed = 0;
hitCollider = false;
ifMoving = false;
xMax = 0;
xMin = 0;
StartCoroutine (waitDown ());
}
}
if (col.tag == "objects2") {
hitCollider2 = true;
metalBox = true;
canMove = false;
hitwoodenC = false;
hitmetalC = true;
moveDown = false;
xMax = 0;
xMin = 0;
if (hascollidedwHouse == true) {
moveDown = false;
isMovingDown = false;
movedownSpeed = 0;
moveupSpeed = 0;
ifMoving = false;
hitCollider2 = false;
xMax = 0;
xMin = 0;
StartCoroutine (waitDown2 ());
}
}
if (col.tag == "pointB") {
if (ifMoving == false) {
moveupSpeed = 0;
movedownSpeed = -4;
} else if (ifMoving == true) {
moveupSpeed = 0;
movedownSpeed = -4;
}
Debug.Log ("Collided");
moveDown = true;
isMovingDown = true;
isMovingUp = false;
canMove = false;
hascollidedwHouse = true;
}
void Move () {
if (isSomethere == false) {
if (isMovingUp == true) {
tiempo += Time.deltaTime;
if (transform.localPosition.x < xMin) {
x = Random.Range (0.0f, velocidadMax);
x = velocidadMax;
tiempo = 0.0f;
Debug.Log ("Left");
}
if (tiempo > 1.0f) { //1.0 0.3
x = -velocidadMax;
tiempo = 0.0f;
Debug.Log ("Right");
}
transform.localPosition = new Vector3 (transform.localPosition.x + x, transform.localPosition.y);
}
} else if (isSomethere == true) {
movedownSpeed = -4;
moveupSpeed = 4;
if (iSPdeath == true) {
movedownSpeed = 0;
moveupSpeed = 0;
}
}
}
void turnFalse ()
{
if( hitCollider == false) {
ifMoving = false; // moves left and right
}
if( hitCollider2 == false) {
ifMoving = false; // moves left and right
}
}
void turnTrue() {
if( hitCollider == false) {
ifMoving = true; // moves up and down
}
if( hitCollider2 == false) {
ifMoving = true; // moves up and down
}
}
IEnumerator wait() {
yield return new WaitForSeconds (2.5f);
hitCollider = false;
if (isMovingUp == true) {
canMove = true;
}
if (isMovingUp == false) {
canMove = false;
moveupSpeed = 0f;
movedownSpeed = -4f;
}
if (canMove == true) {
moveupSpeed = 4f;
}
}
IEnumerator wait2() {
yield return new WaitForSeconds (5.2f);
hitCollider = false;
if (isMovingUp == true) {
canMove = true;
}
if (isMovingUp == false) {
canMove = false;
moveupSpeed = 0f;
movedownSpeed = -4f;
}
if (canMove == true) {
moveupSpeed = 4f;
}
}
IEnumerator waitDown() {
yield return new WaitForSeconds (2.5f);
movedownSpeed = -4f;
moveupSpeed = 0f;
moveDown = true;
}
IEnumerator waitDown2() {
yield return new WaitForSeconds (5.2f);
movedownSpeed = -4f;
moveupSpeed = 0f;
moveDown = true;
}
}
Related
That the User Game View Panel
Here is an Editor view
That the GameObject Movement in all axis, I don't wants that behavior to move in 3-Directions, I just want it to move in either X-axis OR Z_axis
I'm making a 3d game, in which a user can move vehicles using touch-controls that will allows the user to clear the parking area. this script is allied on the camera. this game this is like a 3D_Traffic_Jam_Parking clearance... I'm confused. I just tried to go on multiple learning platforms, but don't get it...!!!
public class ZarSwipe2D_Control : MonoBehaviour
{
#region Variables
private float distance;
private bool isDraging = false;
private bool swipeLeft, swipeRight, swipeUp, swipeDown;
public Vector3 desiredPosition;
private Vector2 Swipe2D;
private Transform Player;
#region Getter-Setter
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
#endregion
#endregion
#region Controller Functionality
private void Update()
{
Vector3 v3;
float x = Swipe2D.x;
float y = Swipe2D.y;
Touch touch = Input.touches[0];
Vector3 pos = touch.position;
if (Input.touchCount != 1)
{
isDraging = false;
return;
}
if (touch.phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay(pos);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider.tag == "Player")
{
Player = hit.transform;
distance = hit.transform.position.z - pos.z;
v3 = new Vector3(pos.x, pos.y, distance);
v3 = Camera.main.ScreenToWorldPoint(v3);
desiredPosition = Player.position - v3;
isDraging = true;
}
}
}
if (isDraging && touch.phase == TouchPhase.Moved)
{
v3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
v3 = Camera.main.ScreenToWorldPoint(v3);
Player.position = v3 + desiredPosition;
}
if (isDraging && (touch.phase == TouchPhase.Ended || touch.phase ==TouchPhase.Canceled))
{
isDraging = false;
}
}
#endregion
}
If you are using a rigidbody component there is an option to disable rotation or movement along 1 axis only
#region Variables
//private float dist; // for old Code
private bool dragging = false;
//private Vector3 offset; // for old Code
private Transform toDrag;
private Vector2 StartSwipePos, EndSwipePos;
#endregion
#region Swipe Controller - Axis Along X&Z
void Update()
{
//Vector3 v3;
if (Input.touchCount != 1)
{
dragging = false;
return;
}
Touch touch = Input.touches[0];
Vector3 pos = touch.position;
if (Input.touchCount == 1)
{
if (touch.phase == TouchPhase.Began)
{
StartSwipePos = touch.position;
dragging = true;
#region OldCode - Touch Begin
//Ray ray = Camera.main.ScreenPointToRay(pos);
//if (Physics.Raycast(ray, out RaycastHit hit))
//{
// if (hit.collider.CompareTag("Player"))
// {
// toDrag = hit.transform;
// dist = hit.transform.position.z - Camera.main.transform.position.z;
// v3 = new Vector3(pos.x, pos.y, dist);
// v3 = Camera.main.ScreenToWorldPoint(v3);
// offset = toDrag.position - v3;
// dragging = true;
// }
//}
#endregion
}
if (dragging && touch.phase == TouchPhase.Moved)
{
EndSwipePos = touch.position;
Ray ray = Camera.main.ScreenPointToRay(pos);
if (Physics.Raycast(ray, out RaycastHit hit))
{
Vector2 Distance = EndSwipePos - StartSwipePos;
float x_Distance = Mathf.Abs(Distance.x);
float Y_Distance = Mathf.Abs(Distance.y);
if (x_Distance > Y_Distance)
{
if (Distance.x > 0)
{
if (hit.collider.CompareTag("Player"))
{
toDrag = hit.transform;
toDrag.transform.Translate(25f * Time.deltaTime, 0, 0);
Debug.Log("Right");
}
}
if (Distance.x < 0)
{
if (hit.collider.CompareTag("Player"))
{
toDrag = hit.transform;
toDrag.transform.Translate(-25f * Time.deltaTime, 0, 0);
Debug.Log("Left");
}
}
}
if (Y_Distance > x_Distance)
{
if (Distance.y > 0)
{
if (hit.collider.CompareTag("Player"))
{
toDrag = hit.transform;
toDrag.transform.Translate(0, 0, 25f * Time.deltaTime);
Debug.Log("Up");
}
}
if (Distance.y < 0)
{
if (hit.collider.CompareTag("Player"))
{
toDrag = hit.transform;
toDrag.transform.Translate(0, 0, -25f * Time.deltaTime);
Debug.Log("Down");
}
}
}
}
#region Old Code - Touch Move
//v3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
//v3 = Camera.main.ScreenToWorldPoint(v3);
//toDrag.position = v3 + offset;
#endregion
}
if (dragging && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled))
{
dragging = false;
}
}
}
#endregion
I want to flip my sprites depending on which direction they are going and then stay in that position until they move again. I've tried velocity detection and the flipping the sprites accordingly, but since my movement is not by force but by changing position it can't detect velocity (I think), so any suggestions would be helpful.
Here's the movement script I've got so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
//DRAG AND DROP
bool isBeingDragged = false;
//POSITIONS AND TARGET
public float speed = 0.5f;
float timer = 0f;
public float waitTime;
public float distanceToAchieve = 0.2f;
bool isFollowing = true;
bool isWaiting = false;
//GOAL TARGET
public GameObject goalGameObject;
Vector2 target;
public Vector2 bounds = new Vector2(1.75f, 3);
private Vector2 RP;
private float startPosX;
private float startPosY;
void Start()
{
if (this.gameObject.tag == "1")
{
transform.position = RandomizePosition();
}
target = RandomizePosition();
isFollowing = true;
}
private void Update()
{
if (!isBeingDragged)
{
if (!isWaiting && Vector2.Distance(transform.position, target) < distanceToAchieve)
{
isWaiting = true;
isFollowing = false;
RandomizeGoal();
}
if (isWaiting)
{
timer += Time.deltaTime;
if (timer > waitTime)
{
timer = 0f;
isWaiting = false;
isFollowing = true;
}
}
}
}
private void FixedUpdate()
{
if (isFollowing && !isBeingDragged)
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
if (isBeingDragged)
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
}
}
Vector2 RandomizePosition()
{
RP = new Vector2(transform.position.x - Random.Range(-1f, 1f), transform.position.y - Random.Range(-1f, 1f));
if (RP.x < bounds.x && RP.x > bounds.x * -1 && RP.y < bounds.y && RP.y > bounds.y * -1)
{
return RP;
}
else
{
return new Vector2(transform.position.x, transform.position.y);
}
}
void RandomizeGoal()
{
waitTime = Random.Range(2, 10);
target = RandomizePosition();
goalGameObject.transform.position = target;
}
private void OnMouseDown()
{
isBeingDragged = true;
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosX = mousePos.x - this.transform.localPosition.x;
startPosY = mousePos.y - this.transform.localPosition.y;
}
private void OnMouseUp()
{
isBeingDragged = false;
GetComponent<Merging>().CheckNearest();
}
}
private void FixedUpdate()
{
if (isFollowing && !isBeingDragged)
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
if (isBeingDragged)
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
// capture the current position of target
// by the way, why you use "loclPosition" for moving ??
// I don't thinkg this is appropriate.
var currentPos = this.gameObject.transform.localPosition;
var newPos = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
// then compare this with new position
bool isLeftSided = false;
if (newPos.x > currentPos.x)
{
isLeftSided = true;
}
else
{
isLeftSided = false;
}
// And figure out the direction . in this example, I wrote just right-left case
// use the y pos for up and down
// then flip the sprite ( this case, default is right sided )
this.gameObject.GetComponent<SpriteRenderer>().flipX. = isLeftSided;
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
}
}
I'm fairly new at Unity and i'm trying to making a game.
I want to have an subtitle fading in when you're at the end of the game. This start when you hit a button.
But when I code a image that I fadein, it plays it directly when you start the game.
Do you guys know a solution?
#pragma strict
private var guiShow : boolean = false;
var car : GameObject;
var rayLength = 10;
var guiObject : GUITexture;
var fadeTime = 1.0;
enum Fade {In, Out}
var fadesubtitles : boolean = false;
function Update ()
{
var hit : RaycastHit;
var fwd = transform.TransformDirection(Vector3.forward);
if(Physics.Raycast(transform.position, fwd, hit, rayLength))
{
if(hit.collider.gameObject.tag == "car")
{
guiShow = true;
if(Input.GetKeyDown("e"))
{
guiShow = false;
}
else if(Input.GetKeyDown("e"))
{
guiShow = false;
}
}
}
else
{
guiShow = false;
}
}
function OnGUI()
{
if(guiShow == true)
{
GUI.Box(Rect(Screen.width / 2, Screen.height / 2, 150, 25), "Press F to escape");
if(Input.GetKeyDown("f")){
fadesubtitles = true;
}
}
}
if (fadesubtitles == true){
yield FadeGUITexture(guiObject, fadeTime, Fade.In);
yield WaitForSeconds(3.0);
yield FadeGUITexture(guiObject, fadeTime, Fade.Out);
}
function FadeGUITexture (guiObject : GUITexture, timer : float, fadeType : Fade) {
if (subtitles == true){
var start = fadeType == Fade.In? 0.0 : 1.0;
var end = fadeType == Fade.In? 1.0 : 0.0;
var i = 0.0;
var step = 1.0/timer;
while (i < 1.0) {
i += step * Time.deltaTime;
guiObject.color.a = Mathf.Lerp(start, end, i)*.5;
yield;
}
}
}
I'd start your game object in the 'disabled' state (uncheck it in the inspector). Then at then end of the game, have some code that enables it.
You can use iTween.
FadeFrom(GameObject target, Hashtable args)
Example:
iTween.FadeFrom(gameObject, iTween.Hash("alpha", 0f, "amount", 1f, "time", 2f));
function OnTriggerEnter(col : Collider){
if(col.tag == "Player")
{
player.transform.position = SpawnPoint.position;
audio.PlayOneShot(Sound);
VioSign.enabled = true;
if(pauseEnabled == false){
pauseEnabled = true;
AudioListener.volume = 1;
Time.timeScale = 0;
Screen.showCursor = true;
}
}
}
This is my respawnpoint script .
#pragma strict
var wheelFL : WheelCollider;
var wheelFR : WheelCollider;
var wheelRL : WheelCollider;
var wheelRR : WheelCollider;
var maxTorque : float = 50;
function Start(){
rigidbody.centerOfMass.y = -0.9;
}
function FixedUpdate () {
wheelRR.motorTorque = maxTorque * Input.GetAxis("Vertical");
wheelRL.motorTorque = maxTorque * Input.GetAxis("Vertical");
wheelFL.steerAngle = 20 * Input.GetAxis("Horizontal");
wheelFR.steerAngle = 20 * Input.GetAxis("Horizontal");
}
Here is my Car Control Script I want to stop the car after respawning again to the respawn point . I'm having a difficult time to solve it. please help me :)
If you just want to stop the car's current movement, you can simply set its velocity to zero:
function OnTriggerEnter(col : Collider){
if(col.tag == "Player")
{
player.transform.position = SpawnPoint.position;
player.gameObject.rigidBody.velocity = Vector3.zero;
audio.PlayOneShot(Sound);
VioSign.enabled = true;
if(pauseEnabled == false){
pauseEnabled = true;
AudioListener.volume = 1;
Time.timeScale = 0;
Screen.showCursor = true;
}
}
}
i am making a game in which i am using is-clicked function when i click the object the letter written on it displayed now i want that when i clicked the same object again the word disappear... now how can i do that?
#pragma strict
static var nextPos = 200;
var word: String;
var sel: String;
var isClicked : boolean=false;
var xpos: float = 200;
function OnMouseDown()
{
if (!isClicked) {
isClicked = true;
xpos = nextPos;
nextPos += 8;
}
}
function OnGUI()
{
if (gameObject.name == "Sphere(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "A");
}
else if (gameObject.name == "Sphere 1(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "B");
}
else if (gameObject.name == "Sphere 2(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "C");
}
else if (gameObject.name == "Sphere 3(Clone)" && isClicked )
{
GUI.Label(new Rect(xpos,260,400,100), "D");
}
}
write in OnMouseDown
else if(isClicked)
{
isClicked = false;
// do your xpos stuff here
}