1.There is a error I am constantly getting. Not a programing error but a error in the sense that my game Object is constantly falling on the ground.
2.Every time I click on a and d(left and right) it moves horizontally.
The script I created with the help of my book L(earning c# by developing games with unity 2021 ) is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavoiur : MonoBehaviour
{
public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
public int hp = 0;
//stores a rigidbody
private Rigidbody _rb;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
}
private float _hInput1;
private float _vInput1;
// Update is called once per frame
void Update()
{
/*MoveForward(_hInput1);
RotateUpWards(_vInput1);
*/
}
/*public void MoveForward(float _vInput)
{
_vInput = Input.GetAxis("Vertical") * MoveSpeed;
this.transform.Translate()
}
public void RotateUpWards(float _hInput)
{
_hInput = Input.GetAxis("Horizontal") * RotateSpeed;
this.transform.Translate(Vector3.forward * _hInput * Time.deltaTime);
}
*/
void FixedUpdate()
{
SetVerticalDirection();
SetHorizontalDirection();
//makes the object move by horizontal input in the up direction
Vector3 rotation = Vector3.up * _hInput1;
/*this is the rotation of the game object
* moving up and then going at a fixed frame rate
*/
Quaternion angleRotation = Quaternion.Euler(rotation * Time.fixedDeltaTime);
//this takes vertical input and addes the position and makes it move forward
//the vertical input is the vertical axis whihc moves at a defined rate tht we can define
_rb.MovePosition(this.transform.position +
this.transform.forward * _vInput1 * Time.fixedDeltaTime);
/*the move rotation moves using the rigibody rotation times the
* horizontal input times and moves up and rotates at the rotate speed rate
*/
_rb.MoveRotation(_rb.rotation * angleRotation);
}
void SetVerticalDirection()
{
_vInput1 = Input.GetAxis("Vertical") * MoveSpeed;
}
void SetHorizontalDirection()
{
_hInput1 = Input.GetAxis("Horizontal") * RotateSpeed;
}
/*Horizontal: ad
* Vertical: ws
*/
}
This code controls the player motion using the input manager for taking vertical and horizontal issue
Related
Hi I am using a rigidbody component attached to my game Object and I don't want to disable gravity but the game object keeps on falling. Moreover the enemy capsule just falls below the ground in my game. Im a little new to unity. The game I am making is with the help of the (Learning c# by developing games unity 2021) this is the 6th version.
The script for the player behaviour is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavoiur : MonoBehaviour
{
public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
public int hp = 0;
/// <summary>
/// stores a rigidbody component for a gameobject
/// </summary>
private Rigidbody _rb;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody>();
_rb.useGravity = true;
}
private float _hInput1;
private float _vInput1;
// Update is called once per frame
void Update()
{
/*MoveForward(_hInput1);
RotateUpWards(_vInput1);
*/
}
/*public void MoveForward(float _vInput)
{
_vInput = Input.GetAxis("Vertical") * MoveSpeed;
this.transform.Translate()
}
public void RotateUpWards(float _hInput)
{
_hInput = Input.GetAxis("Horizontal") * RotateSpeed;
this.transform.Translate(Vector3.forward * _hInput * Time.deltaTime);
}
*/
void FixedUpdate()
{
SetVerticalDirection();
SetHorizontalDirection();
//makes the object move by horizontal input in the up direction
Vector3 rotation = Vector3.up * _hInput1;
/*this is the rotation of the game object
* moving up and then going at a fixed frame rate
*/
Quaternion angleRotation = Quaternion.Euler(rotation * Time.fixedDeltaTime);
//this takes vertical input and addes the position and makes it move forward
//the vertical input is the vertical axis whihc moves at a defined rate tht we can define
_rb.MovePosition(this.transform.position +
this.transform.forward * _vInput1 * Time.fixedDeltaTime);
/*the move rotation moves using the rigibody rotation times the
* horizontal input times and moves up and rotates at the rotate speed rate
*/
_rb.MoveRotation(_rb.rotation * angleRotation);
}
void SetVerticalDirection()
{
_vInput1 = Input.GetAxis("Vertical") * MoveSpeed;
}
void SetHorizontalDirection()
{
_hInput1 = Input.GetAxis("Horizontal") * RotateSpeed;
}
/*Horizontal: ad
* Vertical: ws
*/
}
In the Inspector, you can set gravity scale to 0. Or set the mass to 0. If none works, go to the Rigdid Body and use the Constraints and freeze the y position. this will stop it from falling
I am also currently studying this book. You should check the third box in the RigidBody Freeze Rotation.
I want to rotate my player for where my mouse is pointing and move the player with "WASD" keys.
I'm actually succesfully rotating my player and moving it, but it doesn't move right depending where my mouse is pointing.. the player just move everytime to the same position.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int playerSpeed = 5;
public float sensitivity = 5.0f;
public bool blockMouse = true;
private float mouseX;
void Start(){
BlockMouse();
}
void Update() {
Move();
Rotate();
}
void Move()
{
Vector3 movement = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
transform.position += movement * playerSpeed * Time.deltaTime;
if(Input.GetKeyDown(KeyCode.LeftShift)) {
playerSpeed=10;
} else if(Input.GetKeyUp(KeyCode.LeftShift)) {
playerSpeed=5;
}
}
void Rotate() {
mouseX += Input.GetAxis("Mouse X") * sensitivity;
transform.eulerAngles = new Vector3(0, mouseX, 0);
}
void BlockMouse() {
if (!blockMouse) {
return;
}
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
``
Assuming the rotation is working as you said
transform.position += movement * playerSpeed * Time.deltaTime;
by doing this you change the objects world space absolute position, not taking any rotation into account.
Now there are probably a lot of ways how do rather do this
You could simply take the rotation into account
transform.position += transform.rotation * movement * playerSpeed * Time.deltaTime;
This simply stays in world space but rotates your world space vector accordingly
You could rather use Translate
transform.Translate(movement * playerSpeed * Time.deltaTime);
which basically does the same, takes orientation into account but is not affected by scaling
I'm currently developing an FPS shooter in Unity 3D. I'm fairly new to Unity and I've been having a bit of trouble with my player movement script. Individually everything seems to work, I can rotate and move the player freely, however when I try doing the two simultaneously my player seems to lock and won't rotate.
Sometimes jumping or moving to higher ground on the terrain seems to fix the issue, however I ran a few checks with gravity disabled, no colliders, and with the player well above ground, so the problem seems to be with the script. I've also done a bit of debugging and the Rotate() code does run, just the rotation amount doesn't seem to change.
Here is the player movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
[SerializeField]
private Camera cam;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float looksensitivity = 4f;
[Header("Camera View Lock:")]
[SerializeField] //min and max amount for looking up and down (degrees)
private float lowlock = 70f;
[SerializeField]
private float highlock = 85f;
private Rigidbody rb;
private float currentrotx; //used later for calculating relative rotation
public Vector3 velocity;
public Vector3 rotation; // rotates the player from side to side
public float camrotation; // rotates the camera up and down
public float jmpspe = 2000f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalcMovement();
CalcRotation();
Rotate();
}
void FixedUpdate()
{
Move();
}
private void CalcRotation()
{
float yrot = Input.GetAxisRaw("Mouse X"); //around x axis
rotation = new Vector3(0f, yrot, 0f) * looksensitivity;
float xrot = Input.GetAxisRaw("Mouse Y"); //around y axis
camrotation = xrot * looksensitivity;
}
private void CalcMovement()
{
float xmov = Input.GetAxisRaw("Horizontal");
float zmov = Input.GetAxisRaw("Vertical");
Vector3 movhor = transform.right * xmov;
Vector3 movver = transform.forward * zmov;
velocity = (movhor + movver).normalized * speed;
}
void Move()
{
//move
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
//jump
if (Input.GetKeyDown(KeyCode.Space))
{
//add double jump limit later!
rb.AddForce(0, jmpspe * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void Rotate()
{
//looking side to side
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
// camera looking up and down
currentrotx -= camrotation;
currentrotx = Mathf.Clamp(currentrotx, -lowlock, highlock);
cam.transform.localEulerAngles = new Vector3(currentrotx, 0, 0);
}
}
Here are the relevant components attached to my player:
(The player has a couple more components attached but I ran tests without them and the problem still occurs)
Like I said I'm a bit of a unity novice, so i'm sure I missed something small but I just can't seem to place my finger on it, I've been stuck on this for a while so any help is much appreciated.
SOLVED:
It seems the problem I had was because I was running the scene from my laptop and not a desktop which I assume is what the Unity input was built for.
I have my point of projectile at some height above ground and my enemy(that are moving from right to left and towards the shooting point at horizontal axis) are at ground.The projectile motion that I have it shoots directly in downward motion at angle facing the enemy but I want the projectile to first go upwards and then shoot the enemy.
I have attached the snapshot below:
Here is my code:
using UnityEngine;
using System.Collections;
public class bullet : MonoBehaviour {
public Transform target;
private Transform mytransform;
public GameObject bulletprefab;
public GameObject enemyprefab;
private gamenemy e;
public float firingAngle = 20;
public float gravity = 9.8f;
void Awake()
{
mytransform = transform;
}
// Use this for initialization
void Start () {
mytransform.LookAt(target);
StartCoroutine (project ());
//follow();
}
IEnumerator project()
{ yield return new WaitForSeconds(0.25f);
float target_Distance = Vector3.Distance(mytransform.position * target_Distance , target.position);
// Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * target_Distance * Mathf.Deg2Rad) / gravity);
// Extract the X Y componenent of the velocity
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(target_Distance * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin( 1/target_Distance * Mathf.Deg2Rad);
// Calculate flight time.
float flightDuration = target_Distance / Vx;
// Rotate projectile to face the target.
mytransform.rotation = Quaternion.LookRotation(target.position - mytransform.position);
float elapse_time = 0;
while (elapse_time < flightDuration)
{
mytransform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);
elapse_time += Time.deltaTime;
yield return null;
}
}
Snapshot of how it is with given code:
This is how I want it to be:
Rather than calculating the movement in your code, look at using a Rigidbody on your projectile. Then at the point of firing, apply a force relative to the initial trajectory (i.e direction the gun barrel is facing) and also have gravity affect your bullet.
More on Rigidbodies
I have the following code for my 2D game, it makes object randomly wonder on the screen. What I am having issues with, is when an object looks at the point it is going to, I would like it to rotate as it moves forward. What is happening now, is it rotates instantly to the point it is going towards. So, how can I get it to rotate slowly and move forward at the same time?
using UnityEngine;
using System.Collections;
public class Wonder : MonoBehaviour {
protected Vector2 wayPoint;
protected float speed;
// Use this for initialization
void Start () {
speed = gameObject.GetComponent<Move>().playerSpeed;
wonder();
}
void wonder(){
wayPoint = Random.insideUnitCircle * 10;
}
// Update is called once per frame
void Update () {
Vector2 dir = wayPoint - new Vector2(transform.position.x, transform.position.y);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0,Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - 90));
transform.position = Vector2.MoveTowards(transform.position, wayPoint, Time.deltaTime * speed);
float magnitude = (new Vector2(transform.position.x, transform.position.y) - wayPoint).magnitude;
if(magnitude < 3){
wonder();
}
}
}
Here is an example Image:
So, once the ship gets to its point another will be created and it will move there. I am thinking I will have to have a list of 5+ points, then calculate the arch the ship needs to take adding new points as the ship hits a way point then removing old ones after. I am not sure how to do this though...
using UnityEngine;
using System.Collections;
public class Wander : MonoBehaviour {
protected Vector3 velocity;
protected Vector2 waypoint;
protected float speed;
// Use this for initialization
void Start () {
speed = gameObject.GetComponent<Move>().playerSpeed;
RandomizeWaypoint();
}
void RandomizeWaypoint(){
waypoint = Random.insideUnitCircle * 10;
}
// Update is called once per frame
void Update () {
transform.position = Vector3.SmoothDamp( transform.position, waypoint, ref velocity, Time.deltaTime * speed );
transform.rotation = Quaternion.AngleAxis( Mathf.Atan2( velocity.y, velocity.x ) * Mathf.Rad2Deg, Vector3.forward );
if( Vector3.Distance( transform.position, waypoint ) < 3 ){
RandomizeWaypoint();
}
}
}
Untested. Vector3.SmoothDamp can be pretty handy. Note the spelling also.