Problem; my player acts like im always holding the 'w' key
So I have tried using first person all in one as well as easy fps player controllers. I have double checked the input system using the input system manager and visualizers, have unplugged every usb device aside from my keyboard and mouse and found no inputs out of the ordinary being detected. Even with no usb devices plugged in the player walks.
So, multiple player prefabs in multiple project files, both urp and 3d, will act like a forward walk input is detected even if i have unplugged every usb device. Im at a loss
Make sure that you have not set the velocity as always increasing. Make it increase only when the “w” key is pressed. Here is the code that I use for my player movement -
//Input
float x, y;
bool jumping, sprinting, crouching;
//Movement
public float moveSpeed = 4500;
public float maxSpeed = 20;
private void Update()
{
MyInput();
}
private void MyInput()
{
x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
}
private void Movement()
{
//Extra gravity
rb.AddForce(Vector3.down * Time.deltaTime * 10);
Vector2 mag = FindVelRelativeToLook();
float xMag = mag.x, yMag = mag.y;
CounterMovement(x, y, mag);
//Set max speed
float maxSpeed = this.maxSpeed;
//If speed is larger than maxspeed, cancel out the input so you don't go over max speed
if (x > 0 && xMag > maxSpeed) x = 0;
if (x < 0 && xMag < -maxSpeed) x = 0;
if (y > 0 && yMag > maxSpeed) y = 0;
if (y < 0 && yMag < -maxSpeed) y = 0;
//Some multipliers
float multiplier = 1f, multiplierV = 1f;
// Movement in air
if (!grounded)
{
multiplier = 0.3f;
multiplierV = 0.3f;
}
//Apply forces to move player
rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
}
Hope so this helps.
Thanks.
Related
I am working in unity/C# and trying to make a function that keeps an character in certain x range (-3 to 3). Below isthe code I got to work. Is there a way to simplify it?
//function creation to limit movement in the x axis
float rangeBoundX(int upperBound, int lowerBound, Vector3 i, float horMoveSpe = 0)
{
//will change velocity to keep the x value in the desired range. - velocity to mvoe away from the upper bound and positive velocity goes away from the lowerBound.
if (i.x > upperBound)
{
horMoveSpe = -1;
}
else if (i.x < lowerBound)
{
horMoveSpe = 1;
}
return horMoveSpe;
}
'private void FixedUpdate()'
{
Vector3 enemyforwardMove = transform.forward * enemySpeed * Time.fixedDeltaTime;
Vector3 horizontalMove = transform.position;
magn = rangeBoundX(3, -3, horizontalMove, magn);
horizontalMove = transform.right * magn * freq;
enemyRB.MovePosition(enemyRB.position + enemyforwardMove + horizontalMove);
}
Yes you can use Math.Clamp to bound any value Like this.
void update(){
float xPos = Mathf.Clamp(transform.position.x, -3, 3);
transform.position = new Vector3(xPos, transform.position.y, transform.position.z);
}
using this code you can bound the position of object horizontaly.
Yes, there is a way to simplify it. You can use Mathf.Clamp method https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
example usage: float xPos = Mathf.Clamp(xValue, xMin, xMax);
So, when my i let go off my keys the controller stops like it hits a wall, i tried changing that but all that changed is that now it gets flung into outer space every time i press a key:
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 newMovement = transform.right * x + transform.forward * z;
momentum = new Vector3(characterController.velocity.x, 0, characterController.velocity.z);
newMovement.y = 0;
if (!newMovement.normalized.Equals(momentum.normalized))
{
Debug.Log("new" + newMovement.normalized);
Debug.Log(momentum.normalized);
momentum = (momentum.magnitude - 2f) > 0 ? momentum.normalized * (momentum.magnitude - 2f) : Vector3.zero;
if (newMovement.x == momentum.x)
momentum.x = 0;
if (newMovement.z == momentum.z)
momentum.z = 0;
}
else
momentum = Vector3.zero;
characterController.Move((newMovement * speed + velocity + momentum) * Time.deltaTime);
Also for some reason even though sometimes both vectors are equal they pass through the if statement(i tried using !=)(both vectors are logged on the first 2 lines of the if statement)
Use https://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html, it will gradually slow the movement to zero, depending on the value of smoothTime:
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
private Vector3 newMovement;
void Update()
{
newMovement = transform.right * x + transform.forward * z;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
}
I need to shoot a ball from any height and make it bounce on a target position defined by the user. The angle of launch is also given. I've tried a couple of solutions so far:
Vector3 calcBallisticVelocityVector(Vector3 source, Vector3 target, float angle) {
Vector3 direction = target - source;
float h = direction.y;
direction.y = 0;
float distance = direction.magnitude;
float a = angle * Mathf.Deg2Rad;
direction.y = distance * Mathf.Tan(a);
distance += h/Mathf.Tan(a);
// calculate velocity
float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2*a));
return velocity * direction.normalized;
}
Vector3 calcBallisticVelocityVector2(Vector3 source, Vector3 target, float angle) {
float distance = (target.Planar() - source.Planar()).magnitude;
float a = target.y - source.y - distance;
float halfGravity = -Physics.gravity.magnitude * 0.5f;
float distanceSquared = distance * distance;
float theta = Mathf.Deg2Rad * angle;
float cosSquared = Mathf.Cos(theta) * Mathf.Cos(theta);
float b = distanceSquared / cosSquared;
float speed = Mathf.Sqrt((halfGravity * b) / a);
Vector3 velocity = (target.Planar() - source.Planar()).normalized * Mathf.Cos(theta);
velocity.y = Mathf.Sin(theta);
return velocity * speed;
}
The results I'm getting is that even the ball does go into the direction is expected, it falls earlier than it should be so the speed calculated by these methods seems to be lower than what is actually required to hit the target position.
Rigidbody's mass is set to 1, Gravity is (0, -98, 0), rigid body's drag and angular drag is set to 0. What other variables could be affecting this behavior?
EDIT: One thing I forgot to mention is that I'm setting the resulting vector as rigid body's velocity, so I'm not using via the apply force method.
I adapted code gotten from here: https://answers.unity.com/questions/1131176/projectile-motion.html and now I'm getting the results I was expecting. I can always hit the target position at whatever angle I input.
private Vector3 calcBallisticVelocityVector(Vector3 initialPos, Vector3 finalPos, float angle)
{
var toPos = initialPos - finalPos;
var h = toPos.y;
toPos.y = 0;
var r = toPos.magnitude;
var g = -Physics.gravity.y;
var a = Mathf.Deg2Rad * angle;
var vI = Mathf.Sqrt (((Mathf.Pow (r, 2f) * g)) / (r * Mathf.Sin (2f * a) + 2f * h * Mathf.Pow (Mathf.Cos (a), 2f)));
Vector3 velocity = (finalPos.Planar() - initialPos.Planar()).normalized * Mathf.Cos(a);
velocity.y = Mathf.Sin(a);
return velocity * vI;
}
I am working on adding a helicopter to my 2d game and I need it to move in circular motion whilst moving on the x axis as well. Below you can find the code that I am using which uses the mathematical circle equation.
angle += speed * Time.deltaTime; //if you want to switch direction, use -= instead of +=
float x = startPoint.x + Mathf.Cos(angle) * radius;
float y = startPoint.y + Mathf.Sin(angle) * radius;
transform.position = new Vector2(x + 2, y);
The helicopter is rotating correctly but I can't figure out how I can make it move along the x axis. Concept image of how it should work below:
1) Make an empty game object
2) Parent your box to the empty game object
3) rotate the box around the empty game object
4) move the empty game object to the side
If you want to avoid adding an empty parent, you can keep track of the center of rotation separately, rotate around it, and move it over time.
public class hello_rotate : MonoBehaviour
{
float angle = 0;
float radius = 1;
float speed = 10;
float linear_speed = 1;
Vector2 centerOfRotation;
// Start is called before the first frame update
void Start()
{
centerOfRotation = transform.position;
}
// Update is called once per frame
void Update()
{
centerOfRotation.x = centerOfRotation.x + linear_speed * Time.deltaTime;
angle += speed * Time.deltaTime; //if you want to switch direction, use -= instead of +=
float x = centerOfRotation.x + Mathf.Cos(angle) * radius;
float y = centerOfRotation.y + Mathf.Sin(angle) * radius;
transform.position = new Vector2(x + 2, y);
}
}
So I'm trying to create a realistic trampoline jump instead of the player falling through the trampoline and then slingshotting back up, whilst instead allowing the player to instantly shoot upon contact with the trampoline and come down a relative gravity.
Where am I going wrong and what can I do to fix it?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class small_bounce_script: MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private Vector3 bounce = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
if (bounce.sqrMagnitude > 0) {
moveDirection = bounce;
bounce = Vector3.zero;
} else {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
void OnTriggerEnter(Collider other) {
Debug.Log ("Controller collider hit");
Rigidbody body = other.attachedRigidbody;
// Only bounce on static objects...
if ((body == null || body.isKinematic) && other.gameObject.controller.velocity.y < -1f) {
float kr = 0.5f;
Vector3 v = other.gameObject.controller.velocity;
Vector3 n = other.normal;
Vector3 vn = Vector3.Dot(v,n) * n;
Vector3 vt = v - vn;
bounce = vt -(vn*kr);
}
}
}
A trampoline reacts like a spring device. Let's assume gravity is in Y direction and the trampoline surface is positionied in the X,Z plane.
Then your Y coordinate y is proportional to a sine function during OnTriggerStay. Velocity v in Y direction as 1st derivative of y is then a cosine function, while X and Z velocity remain constant.
y (t) = yMax * sin (f * t)
v (t) = yMax * f * cos (f * t)
Considering conservation of energy, we have:
E = 0.5 * m * vMax² = 0.5 * k * yMax²
=> yMax = ± SQRT (k / m) * vMax
vMax := speed in Y direction when hitting the trampoline. ± because for landing and starting
yMax := maximum amplitude when v == 0, i.e. hwo deep should the player sink before returning
k := spring constant defining trampoline behaviour i.e. how strong it is
m := player's mass
f := SQRT (k / m)
So all you need to do is playing around with the spring constant and have something like this in your Update method:
Vector3 velocity = rigidbody.velocity;
float elapsedTime = Time.time - timestampOnEnter;
velocity.y = YMax * FConst * Mathf.cos (FConst * elapsedTime);
rigidbody.velocity = velocity;
Member var timestampOnEnter is taken in OnTriggerEnter, FConst is the constant we called f in the maths part.