RenderSettings Skybox lerp - unity3d

I want to switch my skybox from a day material to a night material for this I use :
Material night;
int skyboxflag = 0;
int flag = 0;
float t;
public float smooth = 1;
void Start () {
night = Resources.LoadAll("Night_mat",typeof(Material))[0] as Material;
}
void Update () {
if (skyboxflag == 1) {
if(flag == 0){
t = Time.time;
flag = 1;
}
RenderSettings.skybox.Lerp(RenderSettings.skybox, night,(Time.time - t)/smooth);
if(Time.time - t > smooth){
skyboxflag = 0;
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Avatar") {
skyboxflag = 1;
}
}
but nothing happens I keep having the day skybox.
what is the correct way to change the skybox smoothly from a material to another
Thank you

Related

OverlapBoxAll 2d dont detect anything

This script should detect the collision with the colliders of the Hurtbox layer (using OverlapBoxAll)but it does not work I have the matrix layer configured well and the variables assigned in the inspector so I do not know what my error is.
pd: The collision ocurs in HitboxUpdate method
My collision layer matrix 2d:
https://answers.unity.com/storage/temp/173342-sin-titulo.png
The scene and hierarchy:
https://answers.unity.com/storage/temp/173344-scene.png
The script:
public string owner = "-1";
public Vector3 boxSize;
public Vector3 position;
public Quaternion rotation;
public LayerMask mask;
public bool useSphere = false;
public float radius = 0.5f;
public Color inactiveColor;
public Color collisionOpenColor;
public Color collidingColor;
private ColliderState _state;
// ignoreList = ds_List_create()
public float hitStun = 60;
private IHitboxResponder _responder = null;
// Update is called once per frame
void Update()
{
HitboxUpdate();
}
public void StartCheckingCollision()
{
_state = ColliderState.Open;
}
public void StopCheckingCollision()
{
_state = ColliderState.Closed;
}
void OnDrawGizmos()
{
// Draw a yellow sphere at the transform's position
Debug.Log("draw hitbox gizmos");
CheckGizmoColor();
Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, transform.localScale);
if (useSphere)
{
Gizmos.DrawSphere(Vector3.zero, radius); }
else
{
Gizmos.DrawCube(position, new Vector3(boxSize.x * 2, boxSize.y * 2, boxSize.z * 2));
}
}
private void CheckGizmoColor()
{
switch (_state)
{
case ColliderState.Closed:
Gizmos.color = inactiveColor;
Debug.Log("Closed");
break;
case ColliderState.Open:
Gizmos.color = collisionOpenColor;
Debug.Log("Open");
break;
case ColliderState.Colliding:
Gizmos.color = collidingColor;
Debug.Log("colliding");
break;
}
}
public void HitboxUpdate()
{
StartCheckingCollision();
if (_state == ColliderState.Closed)
{
Debug.Log("Collider cloded");
return;
}
Debug.Log("Collider open hit");
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize, transform.eulerAngles.z ,mask);
if (colliders.Length > 0)
{
_state = ColliderState.Colliding;
Debug.Log("We hit something hitbox");
}
if (colliders.Length > 0)
{
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject.GetComponent<Hurtbox>() != null)
{
if (colliders[i].gameObject.GetComponent<Hurtbox>().owner == owner)
{
Debug.Log("collider skiped");
colliders = colliders.Skip(i).ToArray();
}
}
Debug.Log("Hit " + colliders[i].gameObject.name);
}
}
for (int i = 0; i < colliders.Length; i++)
{
Collider2D aCollider = colliders[i];
Debug.Log("Works");
_responder?.CollisionedWith(aCollider);
}
_state = colliders.Length > 0 ? ColliderState.Colliding : ColliderState.Open;
}
public void UseResponder(IHitboxResponder responder)
{
_responder = responder;
}
}
public enum ColliderState
{
Closed,
Open,
Colliding
}
Change
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize, transform.eulerAngles.z ,mask);
to
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, boxSize ,mask);

Unity C# transform.LookAt rotating on wrong axis

Im making the basic foundations of an RPG game. Its point and click, using a navmesh. I have set up the player to move to an enemy and attack when in range. The problem i am having is that when the player reaches the enemy (or the chest/interactable) it rotates on the x axis. Im assuming its something to do with the lookAt function using the pivot point of the target object, but i cannot find a solution. Any help directing me to a solution would be amazing. I have scoured sites, forums and the Unity API for a couple of days now. Im sure its something simple, i just cant seem to see it.
Much love
public class clickToMove : MonoBehaviour
{
// Attack variables
[Header("Attack")]
public float attackDistance;
public float attackRate;
private float nextAttack;
//Navigation variables
private NavMeshAgent navMeshAgent;
//private bool walking;
//Animation variables
private Animator anim;
//Enemy variables
private Transform targetedEnemy;
private bool enemyClicked;
//Interactable variables
private Transform targetedObject;
private bool objectClicked;
void Awake()
{
anim = GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetButton("Fire1"))
{
navMeshAgent.ResetPath();
if(Physics.Raycast(ray, out hit, 1000))
{
if(hit.collider.tag == "Enemy")
{
enemyClicked = true;
targetedEnemy = hit.transform;
}
else if (hit.collider.tag == "Chest")
{
objectClicked = true;
targetedObject = hit.transform;
}
else if(hit.collider.tag == "Player")
{
//walking = false;
navMeshAgent.isStopped = true;
}
else
{
//walking = true;
enemyClicked = false;
navMeshAgent.isStopped = false;
navMeshAgent.destination = hit.point;
}
}
}
if (enemyClicked)
{
MoveAndAttack();
}
else if(objectClicked && targetedObject.gameObject.tag == "Chest")
{
Interaction(targetedObject);
}
else
{
if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
{
//walking = false;
}
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance >= navMeshAgent.stoppingDistance)
{
//walking = true;
}
}
//anim.SetBool("isWalking", walking);
//TODO: needs finishing. Still need to lock it to the y axis to stop its rotation being funny.
if (Input.GetKey(KeyCode.LeftShift))
{
//walking = false;
navMeshAgent.isStopped = true;
transform.LookAt(ray.origin + ray.direction * ((transform.position - Camera.main.transform.position).magnitude * 0.5f));
}
}
// TODO: still a bug where the player rotates 15 deg on x axis when it reaches target. Has something to do with the Lookat function.
void MoveAndAttack()
{
if (targetedEnemy == null)
{
return;
}
navMeshAgent.destination = targetedEnemy.position;
if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance >= attackDistance)
{
navMeshAgent.isStopped = false;
//walking = true;
}
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= attackDistance)
{
//anim.SetBool("isAttacking", false);
transform.LookAt(targetedEnemy);
Vector3 dirToAttack = targetedEnemy.transform.position - transform.position;
if(Time.time > nextAttack)
{
nextAttack = Time.time + attackRate;
//anim.SetBool("isAttacking", true);
}
navMeshAgent.isStopped = true;
//walking = false;
}
}
void Interaction(Transform target)
{
// set target
navMeshAgent.destination = target.position;
//go close to the target
if(!navMeshAgent.pathPending && navMeshAgent.remainingDistance > attackDistance)
{
navMeshAgent.isStopped = false;
//walking = true;
}
//read the info
else if (!navMeshAgent.pathPending && navMeshAgent.remainingDistance <= attackDistance)
{
navMeshAgent.isStopped = true;
transform.LookAt(targetedObject);
//walking = false;
//play animation
//target.gameObject.getComponentInChildren<Animator>().SetTrigger("Open");
objectClicked = false;
navMeshAgent.ResetPath();
}
}
}

How to program custom buttons to navigate through scroll view created with Scroll Rect combined with a Mask

I have a shop GUI, its content in a srollview created with Scroll Rect and Mask combination and can be scrolled down and up.
Right now, the scroll view scrolls by clicking and dragging with the mouse anywhere in scroll view area, or by interacting with a vertical scrollbar.
How do I use custom up and down buttons (circled in red on attached image below) to make the scroll happen?
Copy the following script to your project and apply ScrollRectSnap script to your scroll view . Know if you have done this to make your scroll view snap on button click simply do the following link UpArrowPressed and DownArrowPressed with your up and down buttons and do not forget to check Snap In V parameter in inspector of ScrollRectSnap if you have vertical scrollview and also do not get confused by snapper.DraggedOnRight() call in your DownArrowPressed function as if you have checked Snap In V parameter it will then act like snap down and similler thing with snapper.DraggedOnLeft() other parameters you can set according to your requirment you will have to play with values in order to get it according to your requirments.
public void UpArrowPressed()
{
ScrollRectSnap snapper = GetComponentInChildren<ScrollRectSnap>();
snapper.DraggedOnLeft();
}
public void DownArrowPressed()
{
ScrollRectSnap snapper = GetComponentInChildren<ScrollRectSnap>();
snapper.DraggedOnRight();
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class ScrollRectSnap : MonoBehaviour
{
float[] points;
[Tooltip("how many screens or pages are there within the content (steps)")]
public int screens = 1;
[Tooltip("How quickly the GUI snaps to each panel")]
public float snapSpeed;
public float inertiaCutoffMagnitude;
float stepSize;
ScrollRect scroll;
bool LerpH;
float targetH;
[Tooltip("Snap horizontally")]
public bool snapInH = true;
bool LerpV;
float targetV;
[Tooltip("Snap vertically")]
public bool snapInV = true;
public string controllTag;
bool dragInit = true;
int dragStartNearest;
float horizontalNormalizedPosition;
float verticalNormalizedPosition;
public static event Action<int,int> OnEndReached;
public static event Action<int,int,string> OnEndReachedWithTag;
// Use this for initialization
void Start()
{
Init();
// SnapToSelectedIndex(0);
}
void Init()
{
scroll = gameObject.GetComponent<ScrollRect>();
scroll.inertia = true;
if (screens > 0)
{
points = new float[screens];
stepSize = (float)Math.Round(1 / (float)(screens - 1),2);
for (int i = 0; i < screens; i++)
{
points[i] = i * stepSize;
}
}
else
{
points[0] = 0;
}
}
void OnEnable()
{
}
void Update()
{
horizontalNormalizedPosition = scroll.horizontalNormalizedPosition;
verticalNormalizedPosition = scroll.verticalNormalizedPosition;
if (LerpH)
{
scroll.horizontalNormalizedPosition = Mathf.Lerp(scroll.horizontalNormalizedPosition, targetH, snapSpeed * Time.deltaTime);
if (Mathf.Approximately((float)Math.Round(scroll.horizontalNormalizedPosition,2), targetH))
{
LerpH = false;
int target = FindNearest(scroll.horizontalNormalizedPosition, points);
// Debug.LogError("Target : " + target);
if (target == points.Length-1)
{
if (OnEndReached != null)
{
OnEndReached(1,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(1,target,controllTag);
}
}
else if (target == 0)
{
if (OnEndReached != null)
{
OnEndReached(-1,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(-1,target,controllTag);
}
}
else
{
if (OnEndReached != null)
{
OnEndReached(0,target);
}
if(OnEndReachedWithTag != null)
{
OnEndReachedWithTag(0,target,controllTag);
}
}
}
}
if (LerpV)
{
scroll.verticalNormalizedPosition = Mathf.Lerp(scroll.verticalNormalizedPosition, targetV, snapSpeed * Time.deltaTime);
if (Mathf.Approximately(scroll.verticalNormalizedPosition, targetV))
{
LerpV = false;
}
}
}
public void DragEnd()
{
int target = FindNearest(scroll.horizontalNormalizedPosition, points);
if (target == dragStartNearest && scroll.velocity.sqrMagnitude > inertiaCutoffMagnitude * inertiaCutoffMagnitude)
{
if (scroll.velocity.x < 0)
{
target = dragStartNearest + 1;
}
else if (scroll.velocity.x > 1)
{
target = dragStartNearest - 1;
}
target = Mathf.Clamp(target, 0, points.Length - 1);
}
if (scroll.horizontal && snapInH )
{
targetH = points[target];
LerpH = true;
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
targetH = points[target];
LerpH = true;
}
dragInit = true;
}
public void OnDrag()
{
if (dragInit)
{
if (scroll == null)
{
scroll = gameObject.GetComponent<ScrollRect>();
}
dragStartNearest = FindNearest(scroll.horizontalNormalizedPosition, points);
dragInit = false;
}
LerpH = false;
LerpV = false;
}
int FindNearest(float f, float[] array)
{
float distance = Mathf.Infinity;
int output = 0;
for (int index = 0; index < array.Length; index++)
{
if (Mathf.Abs(array[index] - f) < distance)
{
distance = Mathf.Abs(array[index] - f);
output = index;
}
}
return output;
}
public void DraggedOnLeft()
{
OnDrag();
if (scroll.horizontal && snapInH && scroll.horizontalNormalizedPosition > -0.001f && scroll.horizontalNormalizedPosition < 1.001f)
{
// Debug.Log("Before Press, LerpH : " + LerpH);
if (dragStartNearest < points.Length-1)
{
targetH = points[dragStartNearest+1];
LerpH = true;
}
else
{
targetH = points[dragStartNearest];
LerpH = true;
}
// Debug.Log("After Press, LerpH : " + LerpH);
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
if (dragStartNearest < points.Length-1)
{
targetV = points[dragStartNearest+1];
LerpV = true;
}
else
{
targetV = points[dragStartNearest];
LerpV = true;
}
}
dragInit = true;
}
public void DraggedOnRight()
{
OnDrag();
if (scroll.horizontal && snapInH && scroll.horizontalNormalizedPosition > -0.001f && scroll.horizontalNormalizedPosition < 1.001f)
{
if (dragStartNearest>0)
{
targetH = points[dragStartNearest-1];
LerpH = true;
}
else
{
targetH = points[dragStartNearest];
LerpH = true;
}
}
if (scroll.vertical && snapInV && scroll.verticalNormalizedPosition > 0f && scroll.verticalNormalizedPosition < 1f)
{
if (dragStartNearest > 0)
{
targetV = points[dragStartNearest-1];
LerpV = true;
}
else
{
targetV = points[dragStartNearest];
LerpV = true;
}
}
dragInit = true;
}
public void SnapToSelectedIndex(int index)
{
if (points == null)
{
Init();
}
dragInit = false;
LerpH = false;
LerpV = false;
targetH = points[index];
LerpH = true;
dragInit = true;
}
}

Make objects between camera and character transparent

I'm working on a script for my camera to make objects between itself and the character transparent.
I managed to make it work with RayCast however I don't know how to restablish objects alpha value after they escape the ray.
This is my current code:
private void XRay() {
float characterDistance = Vector3.Distance(transform.position, GameObject.Find("Character").transform.position);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, characterDistance)) {
// Add transparence
Color color = hit.transform.gameObject.renderer.material.color;
color.a = 0.5f;
hit.transform.gameObject.renderer.material.SetColor("_Color", color);
}
}
This is my final code. Note it only makes transparent one object at a time, but the same implementation can easily be done with RaycastAll and using an array for oldHits.
public class Camara : MonoBehaviour {
RaycastHit oldHit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate() {
XRay ();
}
// Hacer a los objetos que interfieran con la vision transparentes
private void XRay() {
float characterDistance = Vector3.Distance(transform.position, GameObject.Find("Character").transform.position);
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, characterDistance)) {
if(oldHit.transform) {
// Add transparence
Color colorA = oldHit.transform.gameObject.renderer.material.color;
colorA.a = 1f;
oldHit.transform.gameObject.renderer.material.SetColor("_Color", colorA);
}
// Add transparence
Color colorB = hit.transform.gameObject.renderer.material.color;
colorB.a = 0.5f;
hit.transform.gameObject.renderer.material.SetColor("_Color", colorB);
// Save hit
oldHit = hit;
}
}
}
I did attach this script to my simple camera following the player. It might help you.
It can actually manage more than one obstructing the view and also you see I pass it a mask which I target with its name instead of checking for the collider name tag. Have fun.
using UnityEngine;
public class followPlayer : MonoBehaviour
{
public Transform player;
public Vector3 offset;
public Transform[] obstructions;
private int oldHitsNumber;
void Start()
{
oldHitsNumber = 0;
}
private void LateUpdate()
{
viewObstructed();
}
void Update()
{
transform.position = player.TransformPoint(offset);
transform.LookAt(player);
}
void viewObstructed()
{
float characterDistance = Vector3.Distance(transform.position, player.transform.position);
int layerNumber = LayerMask.NameToLayer("Walls");
int layerMask = 1 << layerNumber;
RaycastHit[] hits = Physics.RaycastAll(transform.position, player.position - transform.position, characterDistance, layerMask);
if (hits.Length > 0)
{ // Means that some stuff is blocking the view
int newHits = hits.Length - oldHitsNumber;
if (obstructions != null && obstructions.Length > 0 && newHits < 0)
{
// Repaint all the previous obstructions. Because some of the stuff might be not blocking anymore
for (int i = 0; i < obstructions.Length; i++)
{
obstructions[i].gameObject.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
}
}
obstructions = new Transform[hits.Length];
// Hide the current obstructions
for (int i = 0; i < hits.Length; i++)
{
Transform obstruction = hits[i].transform;
obstruction.gameObject.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
obstructions[i] = obstruction;
}
oldHitsNumber = hits.Length;
}
else
{ // Mean that no more stuff is blocking the view and sometimes all the stuff is not blocking as the same time
if (obstructions != null && obstructions.Length > 0)
{
for (int i = 0; i < obstructions.Length; i++)
{
obstructions[i].gameObject.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
}
oldHitsNumber = 0;
obstructions = null;
}
}
}
}

Tiling for a 2D platform in Unity

I was following a tutorial online, and basically the script is telling the gameObject to instantiate a clone of itself if the camera gets to a certain position. The last lines that I am confused about are these
if (rightOrLeft > 0)
{
newBuddy.GetComponent<Tiling>().hasALeftBuddy = true;
}
else
{
newBuddy.GetComponent<Tiling>().hasARightBuddy = true;
}
}
In short, I'm not really up to par with the syntax or math right here. Could someone please help in clearing it up for me?
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(SpriteRenderer))]
public class Tiling : MonoBehaviour {
public int offsetX = 2;
public bool hasARightBuddy = false;
public bool hasALeftBuddy = false;
public bool reverseScale = false;
private float spriteWidth = 0f;
private Camera cam;
private Transform myTransform;
void Awake () {
cam = Camera.main;
myTransform = transform;
}
// Use this for initialization
void Start () {
SpriteRenderer sRenderer = GetComponent<SpriteRenderer>();
spriteWidth = sRenderer.sprite.bounds.size.x;
}
// Update is called once per frame
void Update ()
{
if (hasALeftBuddy == false || hasARightBuddy == false)
{
float camHorizontalExtend = cam.orthographicSize * Screen.width/Screen.height;
float edgeVisiblePositionRight = (myTransform.position.x + spriteWidth/2) - camHorizontalExtend; //sprite width/2..51.2
//(0 + 51.2 - 26.67315 = 24.52685)
//(102.4 + 51.2 - 26.67315 = 126.92685) etc.. //clone of the myTransform
float edgeVisiblePositionLeft = (myTransform.position.x - spriteWidth/2) + camHorizontalExtend; // (0 - 51.2 + 26.67315 = -24.52685)
// (-102.4 - 51.2 + 26.67315 = -126.92685) etc..//clone of the myTransform
if (cam.transform.position.x >= edgeVisiblePositionRight - offsetX && hasARightBuddy == false)
{
MakeNewBuddy (1);
hasARightBuddy = true;
}
else if (cam.transform.position.x <= edgeVisiblePositionLeft + offsetX && hasALeftBuddy == false)
{
MakeNewBuddy (-1);
hasALeftBuddy = true;
}
}
}
void MakeNewBuddy (int rightOrLeft)
{
Vector3 newPosition = new Vector3 (myTransform.position.x + spriteWidth * rightOrLeft, myTransform.position.y, myTransform.position.z);
Transform newBuddy = Instantiate (myTransform, newPosition, myTransform.rotation) as Transform;
if (reverseScale == true)
{
newBuddy.localScale = new Vector3 (newBuddy.localScale.x*-1, newBuddy.localScale.y, newBuddy.localScale.z);
}
if (rightOrLeft > 0)
{
newBuddy.GetComponent<Tiling>().hasALeftBuddy = true;
}
else
{
newBuddy.GetComponent<Tiling>().hasARightBuddy = true;
}
}
}
}
looks to me like the code is telling the current game object that it has a neighbour when the new neighbour is created.
The boolean has a neighbour variables are handy for figuring out that this creation process doesn't need to happen again :)