Tracking distance. Unity 2D game - unity3d

If I have a object that starts at 0 on the x axis, and moving it in the x+ axis. Is there a way I can track that distance made, and use it counter?
I have no clue what im doing, but was thinking something like
var distance = orgpos -> currentpos;
for each x10{
score += 1; }
And this action performed live while moving.
Edit:
calculatedDistance += (transform.position - previousPosition).magnitude;
previousPosition = transform.position;
I have this script that give me the distance, if thats to any help.

Found a way after I posted the question. Ill just post the way I did it for others to use.
//Score
static var score : int = 0;
static var distanceScore : int = 0;
static var starScore : int = 0;
//Adding point and removing star for each collision
function OnCollisionEnter(collision : Collision)
{
if (collision.gameObject.tag == "StarPickup")
{
Destroy(collision.gameObject);
starScore += 10;
}}
// Checking distance
var previousPosition : Vector3;
var calculatedDistance : float;
function Awake()
{
previousPosition = transform.position;
}
function Update()
{
calculatedDistance += (transform.position - previousPosition).magnitude;
previousPosition = transform.position;
distanceScore = Mathf.Round(calculatedDistance/10);
score = distanceScore + starScore;
print("The score is: " + score);
}

Related

Lifting platforms is not working as it should

I would like to make some lifting platforms in my game, so if the platform went down, the characters can't go over it. I have written a script for it, but for some reason the "lifting up" is not working as intended. It won't go back to its starting place, but it will go a bit below. And for some reason it won't go smoothly to the place where it should, just "teleport" there and done. I thougt multiplying Time.deltaTime with a const will help, but it is the same.
Here is my code, any help would be appreciated:
public class LiftingPlatform : MonoBehaviour {
private Transform lift;
private bool isCanBeLifted;
private float timeToLift;
public float timeNeededToLift = 5f;
private Vector3 startPos;
private Vector3 downPos;
private Vector3 shouldPos;
private bool isDown;
public GameObject[] collidingWalls;
// Use this for initialization
void Start () {
lift = transform;
isCanBeLifted = true;
timeToLift = 0f;
isDown = false;
startPos = transform.position;
downPos = new Vector3(startPos.x, startPos.y - 5f, startPos.z);
}
// Update is called once per frame
void Update () {
timeToLift += Time.deltaTime;
if (timeToLift >= timeNeededToLift) {
if (isCanBeLifted) {
if (isDown) {
shouldPos = Vector3.Lerp(startPos, downPos, Time.deltaTime * 10);
lift.position = new Vector3(shouldPos.x, shouldPos.y, shouldPos.z);
isDown = true;
}
else if (!isDown) {
shouldPos = Vector3.Lerp(downPos, new Vector3(startPos.x, startPos.y, startPos.z), Time.deltaTime * 10);
lift.position = new Vector3(shouldPos.x, shouldPos.y, shouldPos.z);
isDown = false;
}
}
timeToLift = 0;
}
if (!isDown) {
for (int i = 0; i < collidingWalls.Length; i++) {
collidingWalls[i].SetActive(true);
}
}
else if (isDown) {
for (int i = 0; i < collidingWalls.Length; i++) {
collidingWalls[i].SetActive(false);
}
}
}
void OnTriggerEnter(Collider collider) {
if (collider.tag == "Player" || collider.tag == "Enemy") {
isCanBeLifted = false;
}
}
void OnTriggerExit(Collider collider) {
if (collider.tag == "Player" || collider.tag == "Enemy") {
isCanBeLifted = true;
}
}
}
These lifting platforms are a child of another Platforms object.
It doesn't look like you are updating the object's position every frame. You are only checking if the total time passed is greater than the time needed to lift, and then updating the position to a value that is dependent on the delta time (using the Vector3.Lerp function).
What I would do is in the update step, if timeToLift is greater then timeNeededToLift, subtract the latter from the former and invert the value of isDown. Then, in your Vector3.Lerp, make the third argument (timeToLift / timeNeededToLift) instead of (Time.deltaTime * 10). Can you try that and see if it works?
The third argument for Vector3.Lerp is the "blending factor" between the two vectors, 0 is the first vector, 1 is the second, and 0.5 is in between. If the total time is greater than the time needed to lift, but the delta time is not greater than 1, it will get the position of the platform using a blending factor of less than 1, resulting in a platform that didn't move fully.

Google Cardboard Magnet Refresh Not Working in Unity3d

I am working on a Unity project using google cardboard, basing my design on Cardboard Catapult, cardboard magnet to make a ball jump and it works the first time, but whenever the game restarts, using Application.LoadLevel(), the ball doesn’t jump anymore; it just glitches. I used this script. I have tested this script (Magnet Sensor Script) with a test application where whenever the magnet is pulled, the text will change color and it works all the time. Here’s my Ball Control Script (the script I called the Magnet Sensing):
#pragma strict
var rotationSpeed = 100;
var jumpHeight = 8;
var Hit01 : AudioClip;
var Hit02 : AudioClip;
var Hit03 : AudioClip;
var distToGround : float;
function Start () {
// Getting the distance from the center to the ground.
distToGround = collider.bounds.extents.y;
}
function Update ()
{
//Handle ball rotation.
var rotation : float = Input.GetAxis(“Horizontal”) * rotationSpeed;
rotation *= Time.deltaTime;
rigidbody.AddRelativeTorque (Vector3.back * rotation);
MagnetSensor.OnMagnetPull += JumpOnMagnet; //important
}
function JumpOnMagnet () { //important
rigidbody.velocity.y = jumpHeight; //important
} //important
function IsGrounded () : boolean { //Check if we are on the ground. Return true if we are else return null.
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}
function OnCollisionEnter () {
var theHit = Random.Range(0, 3);
if (theHit == 0)
{
audio.clip = Hit01;
}
else if (theHit == 1)
{
audio.clip = Hit02;
}
else {
audio.clip = Hit03;
}
audio.pitch = Random.Range (0.9,1.1);
audio.Play();
}
Here’s my script for the restart:
#pragma strict
var maxFallDistance = -10;
private var isRestarting = false;
var level : String;
var GameOverSound : AudioClip;
function Update ()
{
if (transform.position.y <= maxFallDistance)
{
if (isRestarting == false)
{
RestartLevel();
}
}
}
function RestartLevel () {
isRestarting = true;
audio.pitch = 1;
audio.clip = GameOverSound;
audio.Play();
yield WaitForSeconds (audio.clip.length);
Application.LoadLevel(level);
}
Please let me know what the possible issues could be and how I can fix them. Also, I’d appreciate if you can point me to any website or resource that can help.
Don't do MagnetSensor.OnMagnetPull += JumpOnMagnet; in the Update() function. Call it in Start(), so it is only added once.
Also, you should add an OnDestroy() function and call MagnetSensor.OnMagnetPull -= JumpOnMagnet; in it.

I can't configure how high the character jumps. (unity 2d)

I've got a script from a tutorial that makes my player jump when you press a button but I don't know how to configure how high it jumps. Heres the code:
var before : Sprite;
var after : Sprite;
var isGrounded : boolean;
var Animator : Animator;
var character : GameObject;
var jump : float = 0;
var jumpSpeed : float = 5;
var jumpTimer : float = 0;
function Start () {
isGrounded = true;
}
function Update () {
Animator.SetBool("isGrounded", isGrounded);
if(jump == 1) {
jumpTimer = jumpTimer + 1;
}
if(jumpTimer >= 50) {
jumpTimer = 0;
jump = 0;
}
}
function OnMouseDown () {
isGrounded = false;
GetComponent(SpriteRenderer).sprite = after;
if(jump == 0) {
character.GetComponent(Rigidbody2D).velocity.y = jumpSpeed;
jump = 1;
}
yield WaitForSeconds (0.5);
isGrounded = true;
}
function OnMouseUp () {
GetComponent(SpriteRenderer).sprite = before;
}
I tried lowering the floats for jump/jumpspeed/jumptimer but it just won't work. Any ideas?
Placing my comment into an answer for anyone else using the same tutorial and having the same issue.
The line below is used to alter the players y velocity.
character.GetComponent(Rigidbody2D).velocity.y = jumpSpeed;
In order to change the jump height of the player, you will need to alter the jumpSpeed variable.
Note
If you are altering the jumpSpeed variable at the top of the script and it isn't changing, it is because the value in the inspector overrides the value entered at the top of the script.

2D projectile trajectory prediction (unity3d)

(Using unity3d 4.3 2d, it uses box2d like physics).
I have problems with predicting trajectory
I'm using:
Vector2 startPos;
float power = 10.0f;
float interval = 1/30.0f;
GameObject[] ind;
void Start (){
transform.rigidbody2D.isKinematic = true;
ind = new GameObject[dots];
for(int i = 0; i<dots; i++){
GameObject dot = (GameObject)Instantiate(Dot);
dot.renderer.enabled = false;
ind[i] = dot;
}
}
void Update (){
if(shot) return;
if(Input.GetAxis("Fire1") == 1){
if(!aiming){
aiming = true;
startPos = Input.mousePosition;
ShowPath();
}
else{
CalculatePath();
}
}
else if(aiming && !shot){
transform.rigidbody2D.isKinematic = false;
transform.rigidbody2D.AddForce(GetForce(Input.mous ePosition));
shot = true;
aiming = false;
HidePath();
}
}
Vector2 GetForce(Vector3 mouse){
return (new Vector2(startPos.x, startPos.y)- new Vector2(mouse.x, mouse.y))*power;
}
void CalculatePath(){
ind[0].transform.position = transform.position; //set frist dot to ball position
Vector2 vel = GetForce(Input.mousePosition); //get velocity
for(int i = 1; i < dots; i++){
ind[i].renderer.enabled = true; //make them visible
Vector3 point = PathPoint(transform.position, vel, i); //get position of the dot
point.z = -1.0f;
ind[i].transform.position = point;
}
}
Vector2 PathPoint(Vector2 startP, Vector2 startVel, int n){
//Standard formula for trajectory prediction
float t = interval;
Vector2 stepVelocity = t*startVel;
Vector2 StepGravity = t*t*Physics.gravity;
Vector2 whattoreturn = ((startP + (n * stepVelocity)+(n*n+n)*StepGravity) * 0.5f);
return whattoreturn;
}
Using this, I get wrong trajectory.
1. It's like gravity doesn't drag trajectory down at all, and yes i know that gravity is weak because:
t*t*Physics.gravity = 0.03^2 * vector2(0, -9.8) = vector2(0, -0.00882)
But that is the formula :S
2. Since gravity is low, velocity is too strong.
Here is the video:
http://tinypic.com/player.php?v=1z50w3m&s=5
Trajectory formula form:
http://www.iforce2d.net/b2dtut/projected-trajectory
What should I do?
I found that if I set
StepGravity to something stronger like (0, -0.1)
and devide startVel by 8
I get nearly right trajectory, but i don't want that, I need true trajectory path.
Users from answer.unity3d.com said I should ask here, because here is a bigger group of mathematical coders.
And I searched a lot about this problem (that how I found that formula).
you're only calculating the effect of gravity over 1/30th of a second for each step - you need to do it cumulatively. Step 1 should end with a velocity of 0.09G, Step 2 with .18G, step3 with .27G etc.
Here's a very simple example that draws the ballistic trajectory based on start velocity and a supplied time:
using UnityEngine;
using System.Collections;
public class grav : MonoBehaviour {
public Vector3 StartVelocity;
public float PredictionTime;
private Vector3 G;
void OnDrawGizmos()
{
if (G == Vector3.zero)
{
// a hacky way of making sure this gets initialized in editor too...
// this assumes 60 samples / sec
G = new Vector3(0,-9.8f,0) / 360f;
}
Vector3 momentum = StartVelocity;
Vector3 pos = gameObject.transform.position;
Vector3 last = gameObject.transform.position;
for (int i = 0; i < (int) (PredictionTime * 60); i++)
{
momentum += G;
pos += momentum;
Gizmos.DrawLine(last, pos);
last = pos;
}
}
}
In you version you'd want draw your dots where I'm drawing the Gizmo, but it's the same idea unless I'm misunderstanding your problem.

Unity game engine having camera follow script transform change depending on car selected script?

OVERALL GOAL: Have the camera change target to the selected car
I'm new to the unity game engine and got a bit of a problem.
So, I have a successful car selector which changes between cars and starts the match with that car. Everything there works. The only issue is that my "CarCameraScript" has a transform variable which is always 1 of the 3 cars. I want it to change dependant on the selected car.
Here is the look at the code of the CarCameraScript
#pragma strict
var car : Transform;
var distance: float = 6.4;
var height: float = 1.4;
var rotationDamping : float = 3.0;
var heightDamping: float = 2.0;
var zoomRatio : float = 0.5;
var DefaultFOV : float = 60;
private var rotationVector : Vector3;
function Start () {
}
function LateUpdate () {
var wantedAngel = rotationVector.y;
var wantedHeight = car.position.y + height;
var myAngel = transform.eulerAngles.y;
var myHeight = transform.position.y;
myAngel = Mathf.LerpAngle(myAngel,wantedAngel,rotationDamping*Time.deltaTime);
myHeight = Mathf.Lerp(myHeight,wantedHeight,heightDamping*Time.deltaTime);
var currentRotation = Quaternion.Euler(0,myAngel,0);
transform.position = car.position;
transform.position -= currentRotation*Vector3.forward*distance;
transform.position.y = myHeight;
transform.LookAt(car);
}
function FixedUpdate () {
var localVilocity = car.InverseTransformDirection(car.rigidbody.velocity);
if (localVilocity.z<-0.5) {
rotationVector.y = car.eulerAngles.y + 180;
} else {
rotationVector.y = car.eulerAngles.y;
}
var acc = car.rigidbody.velocity.magnitude;
camera.fieldOfView = DefaultFOV + acc*zoomRatio;
}
This is what it looks like on the side panel.
http://i.stack.imgur.com/lYJP7.jpg
The area that says none (transform) is the place that should be variable dependant on the currently selected car.
Now, Here is my other script being the CharacterSelectScript
#pragma strict
//this is the currently selected Player. Also the one that will be saved to PlayerPrefs
var selectedPlayer : int = 0;
function Update()
{
if (Input.GetMouseButtonUp (0)) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
// The pink text is where you would put the name of the object you want to click on (has attached collider).
if(hit.collider.name == "Player1")
SelectedCharacter1(); //Sends this click down to a function called "SelectedCharacter1(). Which is where all of our stuff happens.
if(hit.collider.name == "Player2")
SelectedCharacter2();
if(hit.collider.name == "Player3")
SelectedCharacter3();
}
else
{
return;
}
}
}
function SelectedCharacter1() {
Debug.Log ("Character 1 SELECTED"); //Print out in the Unity console which character was selected.
selectedPlayer = 1;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter2() {
Debug.Log ("Character 2 SELECTED");
selectedPlayer = 2;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter3() {
Debug.Log ("Character 3 SELECTED");
selectedPlayer = 3;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
How would I get it so that the SelectedPlayer changes the transform in the first script?
Any ideas?
I also have the prefab script which probably isnt important.
Also, should I join both scripts into one?
OVERALL GOAL: Have the camera change target to the selected car