Wheel Mesh Not rotating with Wheel Collider - c#

So I'm working on a racing game but first need to get my wheel collider and wheel mesh functioning properly but for some reason they don't appear to be in sync. The wheel colliders rotate for steering and for acceleration but the wheel mesh does not follow, instead it stays idle when testing.
This is the code I have used to get the vehicle moving and wheel colliders spinning which is supposedly meant to make the wheel mesh spin also.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleCougarInfo {
public WheelCollider LeftWheel;
public GameObject LeftWheelMesh;
public WheelCollider RightWheel;
public GameObject RightWheelMesh;
public bool motor;
public bool steering;
}
public class CougarController : MonoBehaviour {
public List<AxleCougarInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;
public void ApplyLocalPositionToVisual(AxleCougarInfo wheelPair)
{
wheelPair.LeftWheelMesh.transform.Rotate (Vector3.left, Time.deltaTime * wheelPair.LeftWheel.rpm * 10, Space.Self);
wheelPair.RightWheelMesh.transform.Rotate (Vector3.right, Time.deltaTime * wheelPair.RightWheel.rpm * 10, Space.Self);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void FixedUpdate() {
float motor = maxMotorTorque * Input.GetAxis ("Horizontal");
float steering = maxSteeringAngle * Input.GetAxis ("Vertical");
foreach (AxleCougarInfo axleInfo in axleInfos)
{
if (axleInfo.steering == true)
{
axleInfo.LeftWheel.steerAngle = steering;
axleInfo.RightWheel.steerAngle = steering;
}
if (axleInfo.motor == true)
{
axleInfo.LeftWheel.motorTorque = motor;
axleInfo.RightWheel.motorTorque = motor;
}
}
}
}

Related

Firing Projectiles in Unity

Im trying to build a weapon in a game using Unity. My bullets spawn but i cant seem to get the force to apply on instantiation to get them to actually fire.
My weapon script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public Rigidbody2D projectile;
public float forceMultiplier;
public Vector2 direction;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
public void Fire(float force, Vector2 direction)
{
Instantiate(projectile, firePoint.position, transform.rotation);
projectile.AddForce(direction * force);
}
// Update is called once per frame
void Update () {
if (timeBtwShots <= 0)
{
if (Input.GetKeyDown(KeyCode.Return))
{
Fire(forceMultiplier, direction);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
You need to add the force to the spawned object and not the prefab.
Your code should be something like this:
public void Fire(float force, Vector2 direction)
{
Rigidbody2D proj = Instantiate(projectile, firePoint.position, transform.rotation);
proj.AddForce(direction * force);
}

My second cube won't run

In my game one normal cube change to a smaler cube.
using UnityEngine;
public class PlayerSkift : MonoBehaviour {
public GameObject myObject1;
public GameObject myObject2;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow))
{
myObject1.SetActive (false);
myObject2.SetActive (true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
myObject2.SetActive(false);
myObject1.SetActive(true);
}
}
}
This code is whats make it do so.
But when i change to my small cube, it won't go anywhere. This scrip makes the cube run.
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
Its on the smaller cube. So the smaller cube follows the bigger, this code:
using UnityEngine;
public class Pl2føglPl1 : MonoBehaviour
{
public Transform player1;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
transform.position = player1.position + offset;
}
}
when the bigger cube disappear, the little one won't start running. Pleas help if you can.
Here's what happens:
public class PlayerMovement
makes normal cube move. But public class PlayerSkift does myObject1.SetActive (false); so normal cube gets deactivated. And it doesn't get void FixedUpdate () event handler fired up anymore. So normal cube doesn't go anywhere, so smaller cube, following it, doesn't go anywhere either.
You need to create some "dummy" invisible GameObject, make your cubes children of if, attach public class PlayerMovement to it, so it always moves, regardless of inner children cubes states. And both children cubes will of course follow their parent's coordinates, since they are positioned relatively to parent. So you only move parent, and no need to synchronize cubes one to another, so you don't need public class Pl2føglPl1 at all.
This is the code i ended up using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSkiftStørelse : MonoBehaviour {
public Vector3 small;
public Vector3 normal;
public Vector3 high;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.DownArrow)) //getkeydown??
{
transform.localScale = small;
}
if (Input.GetKeyDown (KeyCode.UpArrow)) //getkeydown??
{
transform.localScale = normal;
}
}
}

unity3D, enemy following issue

I'm trying to make enemies follow my player when the player enters the radius area of an enemy, but make the enemy stop following when my bullet hits object or enters radiusArea.
See my gif for more detail:
Gif
script:
using UnityEngine;
using System.Collections;
public class FlyEnemyMove : MonoBehaviour
{
public float moveSpeed;
public float playerRange;
public LayerMask playerLayer;
public bool playerInRange;
PlayerController thePlayer;
// Use this for initialization
void Start()
{
thePlayer = FindObjectOfType<PlayerController>();
}
// Update is called once per frame
void Update()
{
flip();
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, moveSpeed * Time.deltaTime);
//Debug.Log(transform.position.y);
}
//Debug.Log(playerInRange);
}
void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, playerRange);
}
void flip()
{
if (thePlayer.transform.position.x < transform.position.x)
{
transform.localScale = new Vector3(0.2377247f, 0.2377247f, 0.2377247f);
}
else
{
transform.localScale = new Vector3(-0.2377247f, 0.2377247f, 0.2377247f);
}
}
}
I hope someone can help me :(
Physics2D.OverlapCircle detects only the collider with the lowest z value (if multiple are in range). So you either need to change the z values so the player has the lowest or you need to work with Physics2D.OverlapCircleAll and check the list to find the player. Or you could change your layers so only the player itself is on that specific layer you feed into the overlap test.

Unity3D Collision in Multiplayer

I'm creating a rocket league like game.
My problem is the ball.
I wrote a scipt who sets up the ball position and rigidbody based on syncvars which the server sets each 0.01 second.
This works well.
The hosting player can touch the ball and it does move on the client aswell.
My code works.
But the problem appears when I'm trying to touch the ball with a client.
The player object glitches into the ball and physics doesn't really work.
The ball gets moved sometimes but it's stil weird movement.
I guess the problem is that the ball doesn't really get the rigidbody changes from the client.
This is my code
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Ball_Behaviour : NetworkBehaviour {
[SyncVar]
public Vector3 syncedballpos;
public Vector3 ballpos;
[SyncVar]
public Quaternion syncedballrot;
public Quaternion ballrot;
public AudioClip boom;
[SyncVar]
public Vector3 syncedballrigvel;
public Vector3 rigvel;
[SyncVar]
public Quaternion syncedballrigrot;
public Quaternion rigrot;
public GameObject ball;
public Rigidbody rig;
public AudioSource aud;
public GameObject pat;
public float offset;
// Use this for initialization
override
public float GetNetworkSendInterval()
{
return 0.015f;
}
void Start () {
aud = GetComponent<AudioSource>();
GetNetworkSendInterval();
ball = this.gameObject;
rig = GetComponent<Rigidbody>();
offset = 1;
}
// Update is called once per frame
void Update ()
{
if (isServer)
{
setball();
}
if (Vector3.Distance(rigvel, syncedballrigvel) > offset)
{
rig.velocity=Vector3.Lerp(rigvel, syncedballrigvel, 1f)*Time.deltaTime*0.05f;
}
else
{
if (Vector3.Distance(ballpos, syncedballpos) > offset)
{
this.transform.position = Vector3.Lerp(ballpos, syncedballpos, 1f) * Time.deltaTime * 0.05f;
}
/* if (Quaternion.Angle(rigrot,syncedballrigrot)>1f)
{
rig.rotation = Quaternion.Slerp(rigrot,syncedballrigrot,0.7f);
}
if (Quaternion.Angle(ballrot, syncedballrot) > 1f)
{
this.transform.rotation = Quaternion.Slerp(ballrot, syncedballrot, 0.7f);
}
*/
}
}
[ServerCallback]
void setball()
{
syncedballrigvel = rig.velocity;
syncedballrigrot = rig.rotation;
syncedballpos = this.transform.position;
syncedballrot = this.transform.rotation;
// RpcDoOnClient(syncedballpos);
}
void OnCollisionEnter(Collision col)
{
aud.Play();
}
public void scored()
{
this.GetComponent<MeshRenderer>().enabled = false;
Instantiate(pat, this.transform.position, this.transform.rotation);
aud.PlayOneShot(boom,2);
}
}

How to make enemies turn and move towards player when near? Unity3D

I am trying to make my enemy object turn and start moving towards my player object when the player comes within a certain vicinity.
For the turning I have been testing the transform.LookAt() function although it isn't returning the desired results as when the player is too close to the enemy object the enemy starts to tilt backwards and I only want my enemy to be able to rotate along the y axis, thanks in advance.
using UnityEngine;
using System.Collections;
public class EnemyController : MonoBehaviour {
public Transform visionPoint;
private PlayerController player;
public Transform Player;
public float visionAngle = 30f;
public float visionDistance = 10f;
public float moveSpeed = 2f;
public float chaseDistance = 3f;
private Vector3? lastKnownPlayerPosition;
// Use this for initialization
void Start () {
player = GameObject.FindObjectOfType<PlayerController> ();
}
// Update is called once per frame
void Update () {
// Not giving the desired results
transform.LookAt(Player);
}
void FixedUpdate () {
}
void Look () {
Vector3 deltaToPlayer = player.transform.position - visionPoint.position;
Vector3 directionToPlayer = deltaToPlayer.normalized;
float dot = Vector3.Dot (transform.forward, directionToPlayer);
if (dot < 0) {
return;
}
float distanceToPlayer = directionToPlayer.magnitude;
if (distanceToPlayer > visionDistance)
{
return;
}
float angle = Vector3.Angle (transform.forward, directionToPlayer);
if(angle > visionAngle)
{
return;
}
RaycastHit hit;
if(Physics.Raycast(transform.position, directionToPlayer, out hit, visionDistance))
{
if (hit.collider.gameObject == player.gameObject)
{
lastKnownPlayerPosition = player.transform.position;
}
}
}
}
change the look at target:
void Update () {
Vector3 lookAt = Player.position;
lookAt.y = transform.position.y;
transform.LookAt(lookAt);
}
this way the look at target will be on the same height as your object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemyMovement : MonoBehaviour
{
public Transform Player;
public float MoveSpeed = 4;
int MaxDist = 10;
int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
// Put what do you want to happen here
}
}
}
}

Categories