The object stops after a spawning - unity3d

How can I stop the object from running after spawning to checkpoint?
function OnTriggerEnter(col : Collider)
{
if(col.tag =="Player")
{
SpawnPoint.position = Vector3(transform.position.x, transform.position.y, transform.position.z);
}
}

I found this over at answers.unity3d.com
What you should do is briefly set the rigidbody to kinematic, as well as brakeTorque for all wheel colliders to Mathf.Infinity and than next update switch it back off and the physics engine should reset any forces causing it to move.
Example from link:
function FixedUpdate()
{
// (if the vehicle has been respanwed this frame,
// then a variable respawned is set to true)
if (respawned)
{
wheelCol.brakeTorque = Mathf.Infinity; // Repeat for all wheelcolliders
rigidbody.isKinematic = true;
respawned = false;
}
else
{
rigidbody.isKinematic = false;
// (do the torque calculations here as usual)
}
}

Related

Why is my raycast not detecting the object?

Im currently on a project where i need to detect if an object is in front of an other, so if it's the case the object can't move, because one is in front of it, and if not the object can move.
So im using here a raycast, and if the ray hit something I turn a bool to true. And in my scene, the ray hits but never turning it to true.
I precise that both of my objects as 2D colliders and my raycast is a 2DRaycast, I previously add to tick "Queries Start in colliders" in physics 2D so my ray won't detect the object where I cast it.
Please save me.
Here is my code :
float rayLength = 1f;
private bool freeze = false;
private bool moving = false;
private bool behindSomeone = false;
Rigidbody2D rb2D;
public GameObject cara_sheet;
public GameObject Monster_view;
public GameObject monster;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Movement();
DetectQueuePos();
}
private void Movement()
{
if(freeze || behindSomeone)
{
return;
}
if(Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Move");
moving = true;
//transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
if(moving)
{
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (!collision.CompareTag("Bar"))
{
return;
}
StartCoroutine(StartFreeze());
}
public void DetectQueuePos()
{
RaycastHit2D hit = Physics2D.Raycast(this.transform.position, this.transform.position + this.transform.up * rayLength, 2f);
Debug.DrawLine(this.transform.position, this.transform.position + this.transform.up * rayLength, Color.red, 2f);
if (hit.collider != null)
{
print(hit.collider.name);
}
if(hit.collider != null)
{
Debug.Log("Behind true");
//Destroy(hit.transform.gameObject);
behindSomeone = true;
}
}
IEnumerator StartFreeze()
{
yield return new WaitForSeconds(1f);
rb2D.constraints = RigidbodyConstraints2D.FreezeAll;
freeze = true;
moving = false;
cara_sheet.SetActive(true);
Monster_view.SetActive(true);
}
While Debug.DrawLine expects a start position and an end position a Physics2D.Raycast expects a start position and a direction.
You are passing in what you copied from the DrawLine
this.transform.position + this.transform.up * rayLength
which is a position, not a direction (or at least it will a completely useless one)! Your debug line and your raycast might go in completely different directions!
In addition to that you let the line have the length rayLength but in your raycasts you pass in 2f.
It should rather be
Physics2D.Raycast(transform.position, transform.up, rayLength)

How do I make the 2D collider not do any function to already colliding objects before level start

In my level, I have a water collider where if you fall in, it triggers a splash effect and water sounds. However, because there is already an object inside the water, whenever I start the level, the water collider triggers and splash and water sounds despite the object already being in the collider.
So, even with the object deep inside the water collider, it creates the splash sound and water effect as if it just fell in.
How do I prevent this?
My code involves OnTrigger2D functions. But how do I make Unity check if an object is already colliding before level load?
Code:
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
gravityoriginal = playerrigidbody.gravityScale;
massoriginal = playerrigidbody.mass;
playerrigidbody.gravityScale = 0.1f;
playerrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
splash.Play(); //Plays the initial splash if velocity is high
underwaterbool.IsUnderwater = true; //stop dust particle
mainmusic.enabled = true;
powerupmusic.enabled = true;
deathmusic.enabled = true;
}
else if (other.tag == "Snatcher")
{
masssnatcheroriginal = snatcherrigidbody.mass;
gravityoriginalsnatcher = snatcherrigidbody.gravityScale;
snatcherrigidbody.gravityScale = 0.1f;
snatcherrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
splashsnatcher.Play();
snatchersounds.enabled = true;
}
else if (other.tag != "Player" && other.tag != "Snatcher" && other.GetComponent<Rigidbody2D>() != null)
{
gravityoriginalbox = other.GetComponent<Rigidbody2D>().gravityScale;
massoriginalbox = other.GetComponent<Rigidbody2D>().mass;
other.GetComponent<Rigidbody2D>().mass = other.GetComponent<Rigidbody2D>().mass + 2f;
other.GetComponent<Rigidbody2D>().gravityScale = 0.1f;
other.GetComponent<ParticleSystem>().Play(false);
splashaudio.Play();
Splashparticlesforbox.IsUnderwaterBox = true;
}
if(other.GetComponent<Rigidbody2D>() != null)
{
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, -0.5f);
}
if (!cooldown)
{
splashaudio.Play();
}
cooldown = true;
StartCoroutine(waittime());
}
Can you post your OnTrigger2D functions code please? Normally Unity does not trigger the OnTriggerEnter method if an object is already inside the trigger when the scene beggins but the OnTriggerStay is executed every frame.
Anyway... one option (not the best one I think) would be to put a boolean propoerty in the trigger that is initialized true and use it to prevent the OnTriggerFunctions to do anything til the fame ends. Then in the LateUpdate method you can set the property as false.
bool m_FirstFrame = true;
void onEnable()
{
m_FirstFrame = true;
}
void OnTriggerEnter2D(Collider2D collision)
{
if(m_FirstFrame){
return;
}
.... //Rest of code
}
//Same for the other OnTrigger2D methods you use
void LateUpdate()
{
m_FirstFrame = false;
}
I hope it helps! Tell me if you need something more, and please, post your code, that way is easier for us to fint where is the issue and get how to fix it.
Good luck ^^

(Unity2D) Switch movement style on collision

I have a player character in a topdown game that moves in grid-like movements (1 unit at a time), but when it hits a patch of ice (square), I want it to switch to lerp-movement, slide to the edge, and stop.
Currently I have 5 different colliders as children for each patch of ice: the ice collider itself, and 4 slightly distanced colliders, one for each side of the ice. When it hits the ice collider, depending on which direction it was heading in, it should lerp to the distanced collider associated.
Like so (it's hard to see the main collider but it's there):
Here is the code I have been using for the down key (its basically the same for all keys):
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
Vector2 movementDown = new Vector2(0, -1);
RaycastHit2D hitDown = Physics2D.Raycast(transform.position, movementDown, 0.05f);
if (hitDown.collider && hitDown.collider.gameObject.tag == "barrier")
{
Debug.Log("N/A");
}
else if (onIce)
{
player.transform.position = Vector3.Lerp(transform.position, downIce.transform.position, 100 * Time.fixedDeltaTime);
}
else
{
player.transform.position += new Vector3(movementDown.x, movementDown.y, -0.1f);
}
}
EDIT: code that updates bool 'onIce':
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "ice") {
onIce = true;
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "ice")
{
onIce = false;
}
}
Lerp is only getting called once, when you push the button. One way to fix it is by using a coroutine:
IEnumerator Slide() {
var t = 0f;
var start = player.transform.position; //we will change the position every frame
//so for lerp to work, we need to save it here.
var end = downIce.transform.position;
while(t < 1f){
t += Time.deltaTime;
player.transform.position = Vector3.Lerp(start, end , t);
yield return null; //returning null waits until the next frame
}
}
And then you use it like this:
...
else if (onIce)
{
this.StartCoroutine(this.Slide());
}
else
...
I think this is still not exactly what you want in your game because it will lerp to the center of the collider. If that's the case you can easily fix it by changing how it calculates the end variable in the coroutine to make the player only slide along the correct axis.

Moving object with raycast issues

I have written a script where a gameobject is intended to move to a raycast.point thrown from the player camera. For the most part this works fine, however there are times (approximately when camera is 45 degrees up from the object) when the object rapidly moves towards the camera (i.e. raycast source).
I have tried a number of approaches attempting to resolve this, however I can’t seem to dig out the root of this issue. Managed to prevent this from occurring by deactivating the collider attached to the object being moved. However I need the collider for various reasons so this approach is not appropriate.
If anyone can provide any pointers as to where I am going wrong I would be incredibly grateful.
NB: coding in uJS
Many thanks in advance, Ryan
function FixedUpdate() {
if (modObj != null && !guiMode) {
//Panel Control
if (!selectObjPanel.activeSelf && !modifySelectObjPanel.activeSelf) //if the selectpanel not open and modSelect not already activated
{
activateModSelectObjPanel(true); //activate it
} else if (selectObjPanel.activeSelf) {
activateModSelectObjPanel(false);
}
//Move
if (Input.GetKey(KeyCode.E)) {
if (Input.GetKeyDown(KeyCode.E)) {
// modObj.GetComponent(BoxCollider).enabled = false;
modObj.GetComponent(Rigidbody).isKinematic = true;
modObj.GetComponent(Rigidbody).useGravity = false;
//
initPos = modObj.transform.position;
var initRotation = modObj.transform.rotation;
}
moveObject(modObj, initPos, initRotation);
} else {
// modObj.GetComponent(BoxCollider).enabled = true;
modObj.GetComponent(Rigidbody).isKinematic = false;
modObj.GetComponent(Rigidbody).useGravity = true;
}
}
}
function moveObject(modObj: GameObject, initPos: Vector3, initRotation: Quaternion) {
//Debug.Log("Moving Object");
var hit: RaycastHit;
var foundHit: boolean = false;
foundHit = Physics.Raycast(transform.position, transform.forward, hit);
//Debug.DrawRay(transform.position, transform.forward, Color.blue);
if (foundHit && hit.transform.tag != "Player") {
//Debug.Log("Move to Hit Point: " + hit.point);
modifyObjGUIscript.activateMoveDisplay(initPos, hit.point);
var meshHalfHeight = modObj.GetComponent. < MeshRenderer > ().bounds.size.y / 2; //helps account for large and small objects
// Debug.Log("CurObj Mesh Min: " + meshHalfHeight);
// modObj.transform.position = hit.point; //***method 01***
// modObj.transform.position = Vector3.Lerp(initPos, hit.point, speed); //***method 02***
// modObj.transform.position = Vector3.SmoothDamp(initPos, hit.point, velocity, smoothTime); //***method 02***
var rb = modObj.GetComponent. < Rigidbody > ();
rb.MovePosition(hit.point); //***method 03***
modObj.transform.position.y = modObj.transform.position.y + meshHalfHeight + hoverHeight;
modObj.transform.rotation = initRotation;
}
}
Turns out the issue was being caused by the raycast hitting the object being moved. Resolved this by only allowing hits from the terrain to be used as points to move to.
if(foundHit && hit.transform.tag == "Terrain")

How to display "stop" message on screen when car reaches at a traffic signal?

I have used box colliders and GUI function... but the problem with box collider is that your car stops after hitting the collider and and I also want message which is displayed on the sceen to be fade away after 10 seconds.
Here's my code:
var msg = false;
function OnCollisionEnter(theCollision : Collision)
{
if(theCollision.gameObject.name == "trafficLight")
{
Debug.Log("collided");
msg=true;
}
}
function OnGUI ()
{
if (msg== true)
{
GUI.Box (Rect (100,0,500,50), "You need to stop if the traffic signal is red");
}
}
but the problem with box collider is that your car stops after
hitting the collider
You should clarify this. Eventually post another question with the specific problem and possibly an SSCCE.
I also want message which is displayed on the sceen to be fade away
after 10 seconds.
Then put something like this inside the Update method of your MonoBehavior:
float timeElapsed;
float timeLimit = 10f;
void Update()
{
if (msg)
{
timeElapsed += Time.deltaTime;
if (timeElapsed >= timeLimit)
{
msg = false;
timeElapsed = 0f;
}
}
}
Alternative, for a more elegant approach, you can use coroutines:
IEnumerator FadeAfterTime(float timeLimit)
{
yield return new WaitForSeconds(timeLimit);
msg = false;
}
void OnCollisionEnter(Collision collision)
{
if(theCollision.gameObject.name == "trafficLight")
{
msg=true;
StartCoroutine(FadeAfterTime(10f));
}
}
From what I understand, you want a stop message to appear on the screen when the player is near a stop sign, so that the player has to stop the car himself.
In order to do this, for starters you'll need to make your box a trigger instead of a collider. There's a small tickbox on the collider of each object which says Trigger. You'll want this to be ticked.
Then put a script similar to this in the trigger box near your traffic light:
var msg = false;
function Start()
{
}
function OnTriggerEnter(theCollision : Collision)
{
if(theCollision.gameObject.name == "car") //where "car" you put the name of the car object
{
msg = true;
StartCoroutine(FadeAfterTime(10f));
}
}
IEnumerator FadeAfterTime(float timeLimit)
{
yield return new WaitForSeconds(timeLimit);
msg = false;
}
function OnGUI ()
{
if (msg== true)
{
GUI.Box (Rect (100,0,500,50), "You need to stop if the traffic signal is red");
}
}
function Update()
{
}
In essence the traffic light trigger box will detect when the car enters the designated area, and will display the GUI, with the fade out script provided by Heisenbug in the previous answer.
I can't test this myself at the moment, but it should work for you. If you have any questions, lemme know.
You should use RayCasting function for this purpose.
I have provided a real example here.
using UnityEngine;
using System.Collections;
public class carMovement : MonoBehaviour {
bool isStop = false;
public float speed = 30f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (!isStop) {
transform.position += (Vector3.forward * Time.deltaTime * speed);
var fwd = transform.TransformDirection (Vector3.forward);
Debug.DrawRay (transform.position, fwd, Color.green);
if (Physics.Raycast (transform.position, fwd, 10)) {
print ("There is something in front of the object!");
isStop = true;
transform.position = transform.position;
}
}
}
}