Refresh to Car Position Correct Way Unity - unity3d

I created car game. I have 3 checkpoint. Car refresh when I press R key
but car wrong position.
My Code;
Checkpoint.js;
#pragma strict
var SpawnPoint : Transform;
function OnTriggerEnter(col: Collider)
{
if(col.tag =="Player")
{
SpawnPoint.position = Vector3(transform.position.x, transform.position.y, transform.position.z);
}
}
ReSpawn.js;
#pragma strict
var SpawnPoint : Transform;
var player : GameObject;
var target : Transform;
function Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
player.transform.position = SpawnPoint.position;
}
}
How to force correct position?

you should use getcomponent to get a var in another script assign your checkpoint script to var script via inspector.
#pragma strict
var script : Checkpoint;
var player : GameObject;
var target : Transform;
function Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
player.transform.position = script.GetComponent(Checkpoint).SpawnPoint.position;
}
}

Related

Unity - Drag with right mouse button?

I am creating a build in Unity 2019.4.12f1 and need to drag an object with Right Mouse button.
My C# skills are very limited, so far but i try.
This scripts is my attempt to be able to rotate a gameobject by holding right mouse button down and dragging ingame.
But it is wrong.
Can anyone help me correct it?ยด
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseM : MonoBehaviour
{
bool dragging = false;
void Start()
{
if (Input.GetMouseButtonDown(1))
{
dragging = true;
}
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
yourOnMouseDownFunction();
dragging = true;
}
if (Input.GetMouseButtonUp(1))
{
yourOnMouseUpFunction();
dragging = false;
}
if (dragging)
{
yourOnMouseDragFunction();
}
}
}
I understood that You need to Drag Object in 3d World so Here is my Code just create new Script and attach to Object You Want to Drag it
Your Object that You need to Drag it should has a collider
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
private void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
mOffset = transform.position - GetMouseWorldPos();
}
private Vector3 GetMouseWorldPos()
{
Vector3 mosePoint = Input.mousePosition;
mosePoint.z = mZCoord;
var result = Camera.main.ScreenToWorldPoint(mosePoint);
return result;
}
}
you can try it by adding it to sphere or cube and if you use custom shape you should insure that the collider is in suitable size or has a meshcollier
Demo
EDIT
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private bool isMouseDragging;
private Vector3 screenPosition;
private Vector3 offset;
private GameObject target;
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject targetObject = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
targetObject = hit.collider.gameObject;
}
return targetObject;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
target = ReturnClickedObject(out hitInfo);
if (target != null)
{
isMouseDragging = true;
Debug.Log("our target position :" + target.transform.position);
//Here we Convert world position to screen position.
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(1))
{
isMouseDragging = false;
}
if (isMouseDragging)
{
//tracking mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//convert screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//It will update target gameobject's current postion.
target.transform.position = currentPosition;
}
}
}
You could try the Input.GetMouseButton method, this should return a value depending on if the button is held pressed.
This one works too, if someone needs in the future.
This is for rotate though.
Sorry, i dont know why it wont let me post as code, so i post an image.
enter image description here

Unity hit.rigidbody reference to concrete gameObject

I've got Menu with 3d texts. Main Camera has got animations that I want to play after clicking on text. Every text has its own rigidbody and collider. I made this code:
#pragma strict
import UnityEngine;
var object : GameObject;
var Run : AnimationPlay;
function start(){
Run = object.GetComponent(AnimationPlay);
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.rigidbody != null){
Debug.Log("Start Game pushed");
Run.action = true;
}
}
}
}
for Start Game button and this one:
#pragma strict
import UnityEngine;
var object : GameObject;
var Run : AnimationPlay2;
function start(){
Run = object.GetComponent(AnimationPlay2);
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.rigidbody != null){
Debug.Log("Back pushed");
Run.action2 = true;
}
}
}
}
for Back button.
The problem is it's no matter on which rigidbody I will click, both animations are starting to play and that makes weird effects. I don't know how to make a reference to concrete gameObject's rigidbody.
I solved my problem. I replaced
hit.rigidbody != null
with
hit.rigidbody.gameObject.tag == "StartGame" //object's tag here
and now it works fine.

How to make a rigid body object you're carrying not go through walls?

I have a player who can carry objects with its gun in a "2.5D Platform Shooter" game but the problem I'm experiencing at the moment is that every time I make the player hold the object(it has a rigid body) and pressed against the wall, the object goes through the wall. Please help unity fans.
This the code I'm using below to carry the object.
#pragma strict
var catchRange = 30.0;
var holdDistance = 4.0;
var minForce = 1000;
var maxForce = 10000;
var forceChargePerSec = 3000;
var layerMask : LayerMask = -1;
#HideInInspector
var anim : Animator;
enum GravityGunState { Free, Catch, Occupied, Charge, Release};
private var gravityGunState : GravityGunState = 0;
private var rigid : Rigidbody = null;
private var currentForce = minForce;
function FixedUpdate()
{
if(gravityGunState == GravityGunState.Free)
{
if(Input.GetButton("Fire1"))
{ anim.SetBool("Shoot", true);
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, catchRange, layerMask))
{
if(hit.rigidbody)
{
rigid = hit.rigidbody;
gravityGunState = GravityGunState.Catch;
}
}
}else if(!hit.rigidbody){anim.SetBool("Shoot", false);}
}
else if(gravityGunState == GravityGunState.Catch)
{
rigid.useGravity = false;
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(!Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Occupied;
}
else if(gravityGunState == GravityGunState.Occupied)
{
if(Physics.Raycast(transform.position, transform.forward, hit, catchRange, layerMask)){
Debug.DrawLine (transform.position, hit.point, Color.red);
}
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Charge;
}
else if(gravityGunState == GravityGunState.Charge)
{
rigid.MovePosition(transform.position + transform.forward * holdDistance);
if(currentForce < maxForce)
{
currentForce += forceChargePerSec * Time.deltaTime;
}
else
{
currentForce = maxForce;
}
if(!Input.GetButton("Fire1"))
gravityGunState = GravityGunState.Release;
rigid.useGravity = true;
}
else if(gravityGunState == GravityGunState.Release)
{
rigid.AddForce(transform.forward * currentForce);
currentForce = minForce;
gravityGunState = GravityGunState.Free;
}
}
#script ExecuteInEditMode()
adding collider to gameObjects will prevent object from moving through each other and if it already has a collider and it is passing through check your settings as follows
Rigidbody Is Kinamatic : False, Is Triggger:false
set the Collision Detection of rigidbody to Continuous or Continuous Dynamic
sometimes for fast moving game objects the collision wont be detected in these sceneraios you can use Raycasting for collisin detection here is DontGoThrough Script that use raycasting for collision detection
using UnityEngine;
using System.Collections;
public class DontGoThroughThings : MonoBehaviour
{
public LayerMask layerMask; //make sure we aren't in this layer
public float skinWidth = 0.1f; //probably doesn't need to be changed
private float minimumExtent;
private float partialExtent;
private float sqrMinimumExtent;
private Vector3 previousPosition;
private Rigidbody myRigidbody;
//initialize values
void Awake()
{
myRigidbody = rigidbody;
previousPosition = myRigidbody.position;
minimumExtent = Mathf.Min(Mathf.Min(collider.bounds.extents.x, collider.bounds.extents.y), collider.bounds.extents.z);
partialExtent = minimumExtent * (1.0f - skinWidth);
sqrMinimumExtent = minimumExtent * minimumExtent;
}
void FixedUpdate()
{
//have we moved more than our minimum extent?
Vector3 movementThisStep = myRigidbody.position - previousPosition;
float movementSqrMagnitude = movementThisStep.sqrMagnitude;
if (movementSqrMagnitude > sqrMinimumExtent)
{
float movementMagnitude = Mathf.Sqrt(movementSqrMagnitude);
RaycastHit hitInfo;
//check for obstructions we might have missed
if (Physics.Raycast(previousPosition, movementThisStep, out hitInfo, movementMagnitude, layerMask.value))
myRigidbody.position = hitInfo.point - (movementThisStep/movementMagnitude)*partialExtent;
}
previousPosition = myRigidbody.position;
}
}

How To Respawn A Prefab After 5 Second's?

I'm trying to spawn a prefab after I destroy the object and only when the object is destroyed.
#pragma strict
function Update () {
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
if (hit.collider.tag == "destroyable") {
Destroy(hit.collider.gameObject);
}
}
}
}
You could put the Prefab in a variable to set on unity editor:
var objectToSpawn : GameObject;
Before the Spawn code you can use:
yield WaitForSeconds (5);
Your code would look something like this:
Javascript
#pragma strict
var objectToSpawn : GameObject;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
if (hit.collider.tag == "destroyable") {
var oldTransform = hit.collider.gameObject.transform;
Destroy(hit.collider.gameObject);
StartCoroutine(SpawnAfter5Seconds(oldTransform));
}
}
}
}
function SpawnAfter5Seconds(oldTransform:Transform)
{
yield WaitForSeconds (5);
var newObject = Instantiate (objectToSpawn , oldTransform.position, oldTransform.rotation);
}

Bullet Decal Sideways

When I instantiate a bullet decal texture to the hit point of a raycast it goes sideways for some reason, no online resources have proved to be any help because it works for them.
The texture for the decal is on a plane and it is laying flat above the ground (height at which raycast hit.)
Here's the raycast shooting code:
var TheDammage = 100;
var BulletHole : Transform;
var canShoot : boolean;
var NoShootZoneTrigger : Transform;
//var AmmoText : GUIText;
var Ammo : float;
var MaxDistanceInMetersMax35 = 25;
var GunFirePistol : AudioClip;
var DryGunFirePistol : AudioClip;
function Start() {
canShoot=true;
}
function Update () {
if (MaxDistanceInMetersMax35>25){
MaxDistanceInMetersMax35 = 35;
}
var hit : RaycastHit;
var ray : Ray =
Camera.main.ScreenPointToRay (Vector3(Screen.width*0.5, Screen.height*0.5,0));
//AmmoText.text = "Bullets Remaining: "+Ammo;
if (Input.GetMouseButtonDown(0)&& canShoot==true){
if (Physics.Raycast(ray, hit, 100)){
if (Ammo >0){
Ammo--;
audio.PlayOneShot(GunFirePistol);
}
{
Debug.Log(hit.distance);
if (hit.distance<MaxDistanceInMetersMax35){
var particleClone = Instantiate(Effect, hit.point,
Quaternion.LookRotation(hit.normal));
Destroy(particleClone.gameObject, 15);
hit.transform.SendMessage("ApplyDammage",
TheDammage, SendMessageOptions.DontRequireReceiver);
}
}
if (Input.GetMouseButtonDown(0)&& canShoot==false){
Debug.Log("No Shooting Zone!");
}
}
if (Input.GetKeyDown("w")){
canShoot = false;
}
if (Input.GetKeyUp("w")){
//animation.Play("GunWalkDone");
canShoot=true;
}
}
if (Ammo<1){
canShoot=false;
if (Input.GetMouseButtonDown(0)&& canShoot==false){
//AmmoText.text="";
audio.PlayOneShot(DryGunFirePistol);
}
}
if (Ammo<18) {
if (Input.GetKeyDown("r")){
animation.Play("Reload");
}
}
}