Why does exporting to Unity WebGL change the speed of objects in my game? - unity3d

GOAL
So I have a space-invaders type game I have made to practise unity and I want to upload it to Itch.io as I have done in the past.
This is a clip of the game.
I switched platforms to WebGL in Build Settings etc, and everything worked fine in Unity.
PROBLEM
However when I built it and uploaded the zip file to Itch.io, the aliens are now a lot faster than usual. (Be aware there may be other things that have changed, I just haven't been able to get to them since it is extremely hard).
CODE
Alien movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AleenController : MonoBehaviour
{
Rigidbody2D rigidbody;
public float speed = 10f;
ScoreController scoreController;
AudioSource aleenDie;
void Start()
{
scoreController = GameObject.Find("Canvas/Score").GetComponent<ScoreController>();
rigidbody = GetComponent<Rigidbody2D>();
aleenDie = GameObject.Find("Main Camera/AleenDie").GetComponent<AudioSource>();
}
void Update()
{
rigidbody.MovePosition(transform.position + new Vector3 (0, -1, 0) * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "laser")
{
aleenDie.Play();
scoreController.score += 1;
Destroy(gameObject);
}
}
}
NOTE
I am really struggling to find out what is wrong here, since everything is fine in unity. If you do need more details just leave a comment.

If you use physics you should
not set or get values via Transform at all
do things in FixedUpdate
In general though in your case instead of using
void Update()
{
rigidbody.MovePosition(transform.position + new Vector3 (0, -1, 0) * speed * Time.deltaTime);
}
at all simply set the velocity once like e.g.
void Start ()
{
...
rigidbody.velocity = Vector3.down * speed;
}
The rest seems to depend a bit on your screen size. Looks like you are moving your elements in pixel space -> the smaller the display the less pixel distance between the top and bottom -> the faster elements seem to travel.

Related

Better movement script needed?

I got an issue that I've been trying to figure out for some time now and still haven't managed. I created a script for movement which besides using the WASD keys also uses two more buttons to go up and down. The thing is - because of the way I added those buttons for some reason no other function regarding position of the player doesn't work well. For example if I put a collider with a simple on trigger transform.position function for the player to hit - the player is placed on that position but then instantly returned back like there was nothing.
Here is my code. I had tons of iterations how this movement can be done. I did it through physics and controller in several ways but nothing helped. Can you guys tell me if it's the code or some hidden Unity synergy that I don't know about?
(this version works around addForce. Regardless, whatever way I make the up and down functions I cannot move the player with script after that.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mov : MonoBehaviour
{
private CharacterController controller;
private Rigidbody Rb;
private Vector3 playerVelocity;
private float playerSpeed =12;
void Start()
{
controller = gameObject.AddComponent<CharacterController>();
Rb = gameObject.GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 add =new Vector3 (0, playerSpeed, 0);
controller.Move(move * Time.deltaTime * playerSpeed);
if (Input.GetKey(KeyCode.Mouse1))
{
Rb.AddForce(0, 1200, 0, ForceMode.Acceleration);
}
if (Input.GetKey(KeyCode.Mouse0))
{
Rb.AddForce(0, -1200, 0, ForceMode.Acceleration);
}
}
}
I'm not sure what you mean by "no other function regarding position of the player doesn't work well" but from have you turning "Collision Detection" in your Rigidbody's settings to "Continuous" and "Interpolate" to "Interpolate"? If you don't do so, Unity's collision's may be a bit funky especially if you are going at high speeds.

Need help refactoring script to find closest target

I have an asteroid field spawned at runtime and droid prefabs the player can release to gather raw material from the asteroids. Everything works but the droids go to the furthest part of the asteroid field to start collecting. I realize I likely need a list of objects to sort through somehow and output the closest.
I suck at coding but managed to get this working by getting a link to the spawned asteroids adding MovementAIRigidbody target to this script & finding one with target = GameObject.Find("AsteroidNew2(Clone)").GetComponent().
This script is based on a GitHub MIT project which is using Vector3 targetPos; I believe to select the target position. Hope this makes sense to a kind soul out there.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityMovementAI
{
public class OffSetPursuitUnityMy : MonoBehaviour
{
MovementAIRigidbody target;
public Vector3 offset;
public float groupLookDist = 1.5f;
SteeringBasics steeringBasics;
OffsetPursuit offsetPursuit;
Separation separation;
NearSensor sensor;
void Start()
{
steeringBasics = GetComponent<SteeringBasics>();
offsetPursuit = GetComponent<OffsetPursuit>();
separation = GetComponent<Separation>();
target = GameObject.Find("AsteroidNew2(Clone)").GetComponent<MovementAIRigidbody>();
sensor = GameObject.Find("SeparationSensor").GetComponent<NearSensor>();
}
void LateUpdate()
{
Vector3 targetPos;
Vector3 offsetAccel = offsetPursuit.GetSteering(target, offset, out targetPos);
Vector3 sepAccel = separation.GetSteering(sensor.targets);
steeringBasics.Steer(offsetAccel + sepAccel);
/* If we are still arriving then look where we are going, else look the same direction as our formation target */
if (Vector3.Distance(transform.position, targetPos) > groupLookDist)
{
steeringBasics.LookWhereYoureGoing();
}
else
{
steeringBasics.LookAtDirection(target.Rotation);
}
}
}
}

2D raycasting in unity doesn't work

So here is the code I've been working on:
using System.Collections.Generic;
using UnityEngine;
public class MovePlayer : MonoBehaviour
{
public float sidewaysForce;
public float jumpingForce;
public Rigidbody2D playerRigidbody;
public Transform playerTransform;
private Vector2 forceToAdd;
private bool onGround;
private LayerMask mask = 8;
private void Start()
{
forceToAdd = new Vector2(0, 0);
}
void FixedUpdate()
{
// Basic left/right movement
forceToAdd.x = 0;
forceToAdd.y = 0;
if (Input.GetKey(KeyCode.A))
{
forceToAdd.x = -sidewaysForce;
}
else if (Input.GetKey(KeyCode.D))
{
forceToAdd.x = sidewaysForce;
}
if (Input.GetKey(KeyCode.Space) && onGround == true)
{
forceToAdd.y = jumpingForce;
onGround = false;
}
var something = Physics2D.Raycast(playerTransform.position, Vector2.down, 200000f, mask.value);
Debug.Log(something.collider);
playerRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse);
}
}
And my issue is this: No matter how far I move the player upwards, whether it be to (0,5) or (0, 2044), it will still print out "Hit ground."
I've tried both Physics and Physics2D, I've tried LayerMasking, everything, and yet it won't work. I'm a beginner to Unity btw.
EDIT: I printed Physics2D.Raycast(playerTransform.position, Vector3.down, 2f).colliderand I ended up with "Player," not "Ground," any way to fix this? I tried increasing the distance to 20 and to 2000, but it yields "Player," still. Any ideas?
EDIT #2: I also tried LayerMasks, didn't work still.
The issue is that you are parsing Physics2D.Raycast the wrong parameters. As you can see in the Unity docs, the function takes a Vector2 and not a Vector3.
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
Also for testing Raycasts in Unity, always set the distance parameter to be Mathf.Infinity until you have designed the solution completely. This will save you a headache in debugging. It is also best practice to add a comment explaining that it is a temporary distance value and that it should be changed later.
When posting your questions in the future on forums, ensure that you properly explain your questions as I really had to look through your code to find what the purpose was.
I am going to refrain from commenting about your code design as this is stack overflow and not reddit but I teach programming at university and would love to help if you are open to leaning :)

Unity ball with constant speed

I'm making 2D mobile game and I have a ball, but my ball doesn't have a constant moving speed. What I need to do?
When I build game on my android device, ball have a various speed. In that case, my game is not playable.
I hope that someone can help me. Thanks.
This is on my start function:
void Start () {
GetComponent<Rigidbody2D> ()
.AddForce (new Vector2 (1f, 0.5f)* Time.deltaTime * force);
}
Is it a good practice if I used in code " Application.LoadLevel ("__Scena_0"); " to load existing scene when I lose " life" ? Problem happens when I lost " life " and try playing game in second chance.
My update function is about OnTriggerEnter2D when my ball hit trigger objects.
EDIT 23.12.2015. : problem solve with adding physics material (fiction 0) and adding to script:
using UnityEngine.SceneManagement;
...
SceneManager.LoadScene ("MainScene");
The problem is the calculation of the force vector:
new Vector2 (1f, 0.5f) * Time.deltaTime * force
You are using Time.deltaTime as a factor, which means that the applied force is not constant, but depending on the deltaTime, which is the duration of the last frame. This explains why it changes randomly.
I don't think Time.deltaTime is what you want here, try just removing the factor and adjusting the "force" factor accordingly. You should now have a constant force applied, independent from the platform you play on.
Create a new Physics Material, set friction zero and add it to your object. If your object has no friction, its speed cannot be decreased. Then, use AddForce() on Rigidbody2D to speed up.
Assuming that your ball and colliding walls have bouncy materials with no friction. Try
public float _ballSpeed = 2.5f;
Rigidbody2D _rb;
void Start()
{
_rb = GetComponent<Rigidbody2D>();
_rb.velocity = Vector2.one * _ballSpeed;
}
void Update()
{
}
From this you can control ball speed through _ballSpeed
//========== OR ==========//
If you want to retain speed even after ball destruction.
Retain _ballSpeed in any global static variable.
Suppose you have a class named Globals, declare a variable like,
public class Globals
{
public static float BALL_SPEED = 2.5f;
}
Now in Ball Script
Rigidbody2D _rb;
void Start()
{
_rb = GetComponent<Rigidbody2D>();
_rb.velocity = Vector2.one * Globals.BALL_SPEED;
}
void Update()
{
}

How to modify the car controllers to do it more Arcade and less realistic in Unity 5 3D

I'm using the Unity 5 Car Asset coming with the Standard Assets. Controls are very hard. The car flips easily even if you are going at quite slow speed.
I have done some "tricks" I have found on the Internet like increasing the mass of the rigid body to 1500, adding the Stabilizer bars (A.K.A. anti-roll bars) script to the car, and setting the gravity center of the car in a fake perfect center. I have included the last versions of those scripts above.
I don't want to simulate perfect physics. I want a fun car easy to ride. Is it possible with Unity?
Script: gravity center of the car in a fake perfect center
using UnityEngine;
using System.Collections;
public class carflipfix : MonoBehaviour {
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().centerOfMass = new Vector3(0, -1, 0);
}
}
Script: stabilizer bars (A.K.A. anti-roll bars).
using UnityEngine;
using System.Collections;
public class AntiRollBar : MonoBehaviour {
public WheelCollider wheelL;
public WheelCollider wheelR;
public float antiRollVal = 5000f;
// Update is called once per frame
void Update () {
WheelHit hit;
float travelL=1.0f;
float travelR=1.0f;
bool groundedL = wheelL.GetGroundHit(out hit);
if (groundedL){
travelL = (-wheelL.transform.InverseTransformPoint(hit.point).y - wheelL.radius) / wheelL.suspensionDistance;
}
bool groundedR = wheelR.GetGroundHit(out hit);
if (groundedR){
travelR = (-wheelR.transform.InverseTransformPoint(hit.point).y - wheelR.radius) / wheelR.suspensionDistance;
}
float antiRollForce = (travelL - travelR) * antiRollVal;
if (groundedL)
GetComponent<Rigidbody>().AddForceAtPosition(wheelL.transform.up * -antiRollForce,
wheelL.transform.position);
if (groundedR)
GetComponent<Rigidbody>().AddForceAtPosition(wheelR.transform.up * antiRollForce,
wheelR.transform.position);
}
}
If we remove the Rigidbody component, we won't be using the Unity physics. Then, we could move the car as we wish getting the input (from the keyboard, gamepad...) to multiply it by the current position of the car. It would be something like:
public class Car: MonoBehaviour
{
public void Update() {
// NOTICE THE FOLLOWING LINE OF CODE IS NOT CORRECT. THE CORRECT WAY SHOULD BE SOMETHING SIMILAR THOUGH:
gameObject.transform.position += input * Time.deltaTime * gameObject.transform.position;
}
}