Tilt GameObject from side to side - c#

I'm having a play with Google Cardboard. I am sitting in a cockpit and I can look around it with no problem.
Now I want to tilt my cockpit from side to side to give a more realistic feel rather than just being stationary.
So far I have this:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 0.25f;
void Update()
{
Tilter ();
}
void Tilter()
{
if (transform.rotation.z < 5f) {
transform.Rotate (new Vector3 (0f, 0f, speed));
}
if (transform.rotation.z > 5f)
transform.Rotate (new Vector3 (0f, 0f, -speed));
}
}
This starts tilting the cockpit to the left as expected, but once the rotation gets bigger than the value of 5, the cockpit does not rotate the other way, it keeps rotating the same way, instead of the opposite direction.

I have not tried this code, but if I understand what you are trying to do, I would suggest to use Mathf.Sin and Time.time to continuously get values in the range of -1 to 1 and then multiply for the rotating range of your cockpit. For example:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 1.0f;
float rotationAngle = 45;
void Update()
{
Tilter ();
}
void Tilter()
{
float rotationZ = rotationAngle * Mathf.Sin(Time.time * speed);
transform.Rotate (new Vector3 (0f, 0f, rotationZ ));
}
}
This example should slowly rotate your cockpit from 0 to 45, then back to 0, then to -45, then back to 0, an so on (again I have not tried it).
You can increase or decrease the value of speed to make the rotation faster or slower.

Related

Netcode for Gameobject: Serverside Movement

I am currently making my first experience with the Netcode for Gameobject package from unity.
I would like to implement a server authorized movement of players. Here I encounter various problems and hope you can help me at this point or give me some food for thought.
So I have a playerprefab which has the network transform component in it. In this I have selected that only the X and Y coordinates should be synchronized.
The first try looked like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerNetwork : NetworkBehaviour
{
Vector3 moveDir = new Vector3(0, 0, 0);
float speed = 10;
void Start()
{
}
void Update()
{
if (!IsOwner) return;
moveDir = new Vector3(0, 0, 0);
if (Input.GetKey(KeyCode.W)) moveDir.y = -1f;
if (Input.GetKey(KeyCode.S)) moveDir.y = +1f;
if (Input.GetKey(KeyCode.A)) moveDir.x = -1f;
if (Input.GetKey(KeyCode.D)) moveDir.x = +1f;
transform.position = moveDir* speed * Time.deltaTime;
}
}
in this attempt, the host can move itself, but the client cannot.
I understood that the client initiates the movement locally, but the Network Transform component synchronizes the server's movement data over it again.
So I assumed I had to tell the server the new position so it would sync the new position to the client.
Thus my next attempt:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerNetwork : NetworkBehaviour
{
Vector3 moveDir = new Vector3(0, 0, 0);
float speed = 10;
void Start()
{
}
void Update()
{
if (!IsOwner) return;
moveDir = new Vector3(0, 0, 0);
if (Input.GetKey(KeyCode.W)) moveDir.y = -1f;
if (Input.GetKey(KeyCode.S)) moveDir.y = +1f;
if (Input.GetKey(KeyCode.A)) moveDir.x = -1f;
if (Input.GetKey(KeyCode.D)) moveDir.x = +1f;
Vector3 pos = moveDir* speed * Time.deltaTime;
moveServerRPC(pos);
}
[ServerRpc]
void moveServerRPC(Vector3 pos)
{
transform.position = pos;
}
}
Now the client can move, but it feels very "hakelig".
It got better after I disabled interpolating on the Network Transform.
Additionally I rewrote the ServerRPC function as follows:
[ServerRpc]
void moveServerRPC(Vector3 pos)
{
transform.Translate(pos);
}
now the movements look smoother but the movement on the client still feels staggered and a bit spongy. Of course, this would be unthinkable for an FPS shooter or similar. But even if it doesn't matter in terms of gameplay, it just doesn't feel good to use.
In the respective readings, it is always recommended to control the movement via a Client Network Transform component, but at the same time it is not recommended to do so in competitive games. Unfortunately, I can't find any examples of this.
How would one proceed here? How far off is my idea and what would have to be changed to get a fluid but server controlled movement?

trying to make a mouse rotation script in unity, but it does nothing

Im making a 3d platformer In unity as my first game, and I'm trying to add some mouse rotation, but don't know what to do. the problem is it literally will not rotate.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PCM : MonoBehaviour
{
public float speed = 10.0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float translation = Input.GetAxis("MouseX") * speed;
float straffe = Input.GetAxis("MouseY") * speed;
translation *= Time.deltaTime;
straffe *= Time.deltaTime;
transform.Translate(straffe, 0, translation);
}
}
all player propeties
I assume, since you said "platform" that you're doing 2D. You had
transform.Translate(straffe, 0, translation);
Usually, 2D works on X- (left/right) and Y- (up/down) axes (and Z is "in/out"). Try
transform.Translate(straffe, translation, 0);

How can I rotate an object from on one axis randomly between two directions?

I want to create effect like the object is looking around.
Like it's inspecting around. In this he is looking at a window so the idea is to make like he is looking the view outside.
This is a screenshot of the Navi looking at the window :
The camera is positioned out of the window looking forward on the Navi face:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemAction : MonoBehaviour
{
public float xAngle, yAngle, zAngle;
public float speed;
public camMouseLook mouselook;
public GameObject lockedRoomCamera;
public Camera playerCamera;
public GameObject navi;
private bool torotate = false;
public void Init()
{
navi.transform.parent = null;
navi.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
navi.transform.Rotate(new Vector3(0, 180, 0));
PlayerController.disablePlayerController = true;
mouselook.enabled = false;
playerCamera.enabled = false;
lockedRoomCamera.SetActive(true);
torotate = true;
}
private void Update()
{
if(torotate == true)
{
navi.transform.Rotate(xAngle, Random.Range(90, 270) * speed * Time.deltaTime, zAngle, Space.Self);
}
}
}
I want to rotate the object only on the y axis randomly between 90 degrees and 270 degrees. So it will looks like the object is looking to the sides left and right.
But now the object is just spinning nonstop on one direction to the left.
One way is to use a coroutine to generate random rotations every so often and then lerp to them over time:
IEnumerator DoLookAround()
{
float lookPeriod = 5f; // change look every 5 seconds
float maxRotationSpeed = 90f; // turn no faster than 90 degrees per second
Vector3 neutralForward = transform.forward;
while(true)
{
float timeToNextLook = lookPeriod;
while (timeToNextLook > 0) {
// Get random offset from forward
float targetYRotation = Random.Range(-90f, 90f);
// calculate target rotation
Quaternion targetRotation = Quaternion.LookRotation(neutralForward, transform.up)
* Quaternion.AngleAxis(targetYRotation, Vector3.up);
// rotate towards target limited by speed
Quaternion newRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, maxRotationSpeed * Time.deltaTime);
timeToNextLook -= Time.deltaTime;
yield return null;
}
}
}
Then you can call it with:
StartCoroutine("DoLookAround");
and stop it with
StopCoroutine("DoLookAround");

2D Ricochet Physics not working in Unity

I am trying to make a game where a ball will be ricocheting off several different colliders on screen. Based on what I researched I got some code that seemed to make sense at first but does not seem to work at all. I am testing it out just by having the ball fall down onto a 2D floor with a box collider attached to it. However once it collides with the floor it just stops there and doesn't bounce back up. I tried disabling "Queries Start in Colliders" in the project settings and offsetting the origin position of the RaycastHit2D so that it would not detect the collider its attached to but that still didn't work. I don't think the RaycastHit2D is working at all because it doesn't even display anything in the console. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehavior : MonoBehaviour {
Rigidbody2D rigidbody;
public Vector2 startPos;
public float speed;
public float hitOffset;
Vector3 vector = new Vector3(0, 5,0); //used to offset origin point of RaycastHit2D hit
private void OnEnable()
{
rigidbody = GetComponent<Rigidbody2D>();
this.transform.position = startPos;
}
private void Update()
{
transform.Translate(Vector2.down * speed * Time.deltaTime);
RaycastHit2D hit = Physics2D.Raycast(transform.position + vector, - transform.up, speed * Time.deltaTime + hitOffset);
Debug.DrawRay(transform.position, -transform.up, Color.red);
Ray2D ray = new Ray2D(transform.position, -transform.up);
if (hit)
{
Debug.Log(speed * Time.deltaTime + hitOffset);
Debug.Log(hit.collider.name);
Vector2 reflectDir = Vector2.Reflect(ray.direction,hit.normal);
float rotation = Mathf.Atan2(reflectDir.y, reflectDir.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0, 0, rotation);
}
}
}
Is my math bad? Any help is very appreciated, thanks.

Unity 5.1 player control of secondary object relative to player object

I've done a lot of searching but can't find a sollution to this problem.
What I want is to control a game object that rotates around the player object at a fixed distance based on right analogue stick input, indepentant of player movement. I also want the object to face outwards as it moves around the player.
I have left analogue stick set to player movement and working and have right analogue stick set up and tested so I know the input is working.
I've tried transform.rotate, RotateAround, .position and quaternions etc but can't figure it out or find anything that might help. I am fairly new to this so there's probably a simple sollution, I just can't see it!
Appreciate any help you might be able to give :) Thanks a mil
EDIT 2: The second attempt
so I've got this so far now:
public class ShieldMovement : MonoBehaviour {
public Transform target; //player shield is attaced to
float distance = 0.8f; // distance from player so it doesn't clip
Vector3 direction = Vector3.up;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float angle = Mathf.Atan2 (Input.GetAxisRaw("rightH"), Input.GetAxisRaw("rightV"))* Mathf.Rad2Deg;
if(Input.GetAxis("rightH") != 0f || Input.GetAxis("rightV") != 0f)
{
direction = new Vector3(Input.GetAxis("rightH"),Input.GetAxis("rightV"), 0.0f ) ;
}
Ray ray = new Ray(target.position, direction);
transform.position = ray.GetPoint(distance);
if(Input.GetAxis("rightH") != 0f || Input.GetAxis("rightV") != 0f)
{
transform.rotation = Quaternion.AngleAxis(angle,Vector3.forward*-1);
}
}
}
I'd like it to be a smooth rotation of the shield around the player going to a new location instead of teleporting there. I've tried some lerps and some slerps, so far all I've been able to so is interpolate from one point on the circumference in a direct line to the new point. Can't think of a way to get it to rotate around the player as it does if you just rotate the stick. Hope that makes sense!
Any ideas you wonderful folk you?
Heres two ways of accomplishing what you want
Please note: this has not been tested
With a custom normalized procession (0f is exactly Vector3.forward, 1f brings you back to Vector3.forward)
using UnityEngine;
using System.Collections;
public class Follower : MonoBehaviour {
float distance = 10f;
Vector3 direction = Vector3.forward;
float procession = 0f; // exactly at world forward 0
Transform target;
void Update() {
float circumference = 2 * Mathf.PI * distance;
angle = (procession % 1f) * circumference;
direction *= Quaternion.AngleAxis(Mathf.Rad2Deg * angle, Vector3.up);
Ray ray = new Ray(target.position, direction);
transform.position = ray.GetPoint(distance);
transform.LookAt(target);
}
}
With Input.GetAxis
using UnityEngine;
using System.Collections;
public class Follower : MonoBehaviour {
float distance = 10f;
Vector3 direction = Vector3.forward;
float speed = .01f;
Transform target;
void Update() {
direction *= Quaternion.AngleAxis(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Vector3.up);
Ray ray = new Ray(target.position, direction);
transform.position = ray.GetPoint(distance);
transform.LookAt(target);
}
}

Categories

Resources