How can I repeat this boost (push)? - c#

I dont understand how I can make this shotgun jumps in my version of Unity: https://www.youtube.com/watch?v=FUkdz8jYt3w
How does this work?
Im using "First Person Controller" that looks like capsule
There are images: https://imgur.com/a/uvfAePX
This is for old version of Unity 4.5.5. I've tried RigidBody, but nothing happened. I've tried Transform, but again, no result.
First Person Controller:
using UnityEngine;
using System.Collections;
public class run : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
public Transform character;
public int CharacterForce = 5000;
public int time = 1;
void Update()
{
CharacterController controller =
GetComponent<CharacterController>();
if (controller.isGrounded)
{
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);
if (Input.GetMouseButtonDown(0))
{
Transform BulletInstance = (Transform)Instantiate(character, GameObject.Find("CameraRSP").transform.position, Quaternion.identity);
BulletInstance.GetComponent<Rigidbody>().AddForce(transform.forward * CharacterForce);
}
}
}
"Grenade" code:
using UnityEngine;
using System.Collections;
public class grenade : MonoBehaviour
{
public Transform GrenadeF;
public int force = 500;
public float radius;
void Start()
{
Collider[] col = Physics.OverlapSphere(transform.position, radius);
foreach (Collider c in col)
{
c.GetComponent<Rigidbody>().AddExplosionForce(force, transform.position, radius);
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, radius);
}
}
When I used Transform I expected that this would work in ANY direction, but it worked in only one.
When I used RigidBody I expected that this would WORK, but my capsule didnt even moved.

Checkout the optional upwardsModifier parameter of
AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier = 0.0f, ForceMode mode = ForceMode.Force));
(The API for Unity 4 is no longer available but I guess it should have been the same there)
Adjustment to the apparent position of the explosion to make it seem to lift objects.
and
Using this parameter, you can make the explosion appear to throw objects up into the air, which can give a more dramatic effect rather than a simple outward force. Force can be applied only to an active rigidbody.
By default it is 0 so if you don't pass it there won't be any upwards force.
As you can see in the example from the API
Vector3 explosionPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
// |
// v
if (rb) rb.AddExplosionForce(power, explosionPos, radius, 3.0f);
}
they passed e.g. 3.0f as upwardsModifier. This makes the explosion
appear to be centred 3.0 units below its actual position for purposes of calculating the force direction (ie, the centre and the radius of effect are not modified).
Note: Typed on smartphone so no warrenty but I hope the idea gets clear

Related

How to make a rigidbody moving at a constant speed using the velocity function go up and down slopes?

In my game, I have a vehicle using a rigidbody that moves forward (relative to the front of the vehicle) at a constant rate using the rigidbody velocity function. The vehicle also may turn 90 degrees to the right and back, of course causing the direction it is moving to rotate. The vehicle drives on a floating platform, and if driven off, the velocity function is stopped so that the car may properly fall off using rigidbody physics.
I want to have slopes at various points in the game, and since the vehicle moves at a constant speed, the vehicle should be able to drive up and down a slope automatically. The issue is that I have to directly control the rigidbody's velocity to make it drive at a constant speed, so when the vehicle drives into a slope, the velocity function keeps pushing it forward without properly rotating, not letting it properly drive up the slope. How should I go about fixing this? Should I be using the rigidbody velocity function at all in this case?
For reference, here is the script I am using for vehicle movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField] private GameObject followCamera;
[SerializeField] private AnimationCurve lerpCurve;
[SerializeField] private float turnSpeed;
[SerializeField] private float speed;
private static float turnTimer = 2f;
private float turnTimeElapsed;
private float clampedTimeElapsed;
private float lerpTimer;
Rigidbody ridgy;
LayerMask groundLayer;
private void Start()
{
groundLayer = LayerMask.GetMask("Ground");
ridgy = this.GetComponent<Rigidbody>();
turnTimeElapsed = 0f;
Quaternion endRot = Quaternion.Euler(0f, 90f, 0f);
}
private void Update()
{
if (Input.GetKey(KeyCode.Space) && turnTimeElapsed < turnTimer)
{
turnTimeElapsed += turnSpeed * Time.deltaTime;
}
else if (!Input.GetKey(KeyCode.Space) && turnTimeElapsed > 0)
{
turnTimeElapsed -= turnSpeed * Time.deltaTime;
}
clampedTimeElapsed = Mathf.Clamp(turnTimeElapsed, 0f, turnTimer);
lerpTimer = clampedTimeElapsed / turnTimer;
lerpTimer = lerpCurve.Evaluate(lerpTimer);
}
private void FixedUpdate()
{
if (Physics.CheckBox(transform.position, new Vector3(.5f, .5f, .5f), Quaternion.identity, groundLayer))
{
if (lerpTimer > 0f && lerpTimer < .75f)
{
speed = 45;
}
else
{
speed = 15;
}
ridgy.rotation = new Quaternion
(
0,
Mathf.Sin(lerpTimer * Mathf.PI / 4f),
0,
Mathf.Cos(lerpTimer * Mathf.PI / 4f)
);
ridgy.velocity = transform.forward * speed;
}
else
{
followCamera.GetComponent<CameraFollow>().enabled = false;
return;
}
}
}

Rotate enemy character to see player character

I am making the enemy character to follow the player character.
In the FixedUpdate method the enemy character move toward the player character,
then in the Update method character rotates to the player character.
However, with this script, somehow enemy character is just nudging and gets stuck.
Where is the mistake, what's wrong???
public class enemy : MonoBehaviour
{
GameObject tObj;
private Vector3 latestPos;
public string targetObjectName;
public float speed = (float)1.0;
void Start()
{
tObj = GameObject.Find("player");
latestPos = transform.position;
}
void Update()
{
Vector3 diff = transform.position - latestPos;
latestPos = transform.position;
if (diff.magnitude > 0.01f)
{
transform.rotation = Quaternion.LookRotation(diff);
}
}
void FixedUpdate(){
Vector3 dir = (tObj.transform.position - this.transform.position).normalized;
float vx = dir.x * speed;
float vz = dir.z * speed;
this.transform.Translate((float)(vx / 50.0),0,(float)(vz / 50.0));
}
}
Use Package Manager "Standard Assets", Inside Unity put two FPSController one should be Player and the second can be Enemy.
I know this does not answers your question but its a faster way to ad Enemy.
AI Settings
Just remove the camera, Audio Source and First Person Controller Script as in image.
The Code for AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowAI : MonoBehaviour
{
public CharacterController _controller;
public Transform target;
public GameObject Player;
[SerializeField]
float _moveSpeed = 2.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update() {
Vector3 direction = target.position - transform.position;
direction = direction.normalized;
Vector3 velocity = direction * _moveSpeed;
_controller.Move(velocity * Time.deltaTime);
Vector3 lookVector = Player.transform.position - transform.position;
lookVector.y = transform.position.y;
Quaternion rot = Quaternion.LookRotation(lookVector);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, 1);
}
}

Player gravity turns off while i move in Unity

I am quite new to unity and I have two scripts, one for gravity and one for player movement as the names suggest. The reason I am using a gravity script is that the third person movement doesn't support using a rigidbody with position and rotation enabled, so I have frozen the position and the rotation inside the rigidbody (which turns off gravity in the rigidbody). I made the Gravity script myself but I followed a tutorial on the player movement script because I have no idea how to make third person movement so I don't really know what is going on in the movement script.
Movement script:
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
UnityEngine.Vector3 direction = new UnityEngine.Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = UnityEngine.Quaternion.Euler(0f, angle, 0f);
UnityEngine.Vector3 moveDir = UnityEngine.Quaternion.Euler(0f, targetAngle, 0f) * UnityEngine.Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
Gravity script:
public class gravityScript : MonoBehaviour
{
public float GravitySpeed = -0.03f;
public bool GravityCheck = false;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Terrain0_0")
{
GravityCheck = true;
}
}
void OnCollisionExit(Collision col)
{
GravityCheck = false;
}
void Update()
{
if (GravityCheck == false)
{
transform.Translate(0, GravitySpeed, 0);
}
}
}
Thank you in advance :)
I don't know what happened but when I opened it today (the day after posting) it was working fine. It was likely just a bug that got fixed after a restart.

Can't rotate and move at the same time

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.

transform.Translate isn't cutting it and rigidbody.AddRelativeForce doesn't move my character (Unity and c#)

I'm making a game in Unity 5 (3D) and am using c# for scripting. So I basically have a third person dude running around with 8 direction controls (WASD) and the way I have set it up now is like this (ignore all the public variables for testing):
public class Player8D : MonoBehaviour
{
public float moveSpeed;
public float moveSpeedMax = 13.5F;
public float turnSpeed = 4F;
public float transitionSpeed = 10F;
private float moveSmooth = 0.0F;
public float moveSmoothTime = 10F;
private Animator anim;
private Rigidbody rb;
private CharacterController cc;
void Start()
{
anim = gameObject.GetComponentInChildren<Animator>();
rb = gameObject.GetComponentInChildren<Rigidbody>();
cc = gameObject.GetComponentInChildren<CharacterController>();
}
void Update()
{
Vector3 NextDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (NextDir != Vector3.zero) //When movement input is happening
{
anim.SetInteger("Run", 1); //Animation stuff
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(NextDir), Time.deltaTime * turnSpeed);
moveSpeed = Mathf.SmoothDamp(moveSpeed, moveSpeedMax, ref moveSmooth, moveSmoothTime / 100);
} else
{
moveSpeed = Mathf.SmoothDamp(moveSpeed, 0.00F, ref moveSmooth, transitionSpeed / 100);
anim.SetInteger("Run", 0); //Animation stuff
anim.CrossFade("Idle", transitionSpeed / 100);
}
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed); //Movement code
}
}
This gave me the best feeling due to how it moves in the direction it's facing, rather than in 8 distinct world directions like with cc.Move. That being said it has the caveat of not being in physics, which I kinda need for OnTriggerEnter and falling realistically and it makes going uphill strange. I have no idea how to manage the rb.AddForce or AddRelativeForce functions, as they don't move my character when I replace transform.Translate with them, no matter how great the force is.
How do I change the code and components to get my character moving through physics?
Here is a screenshot of my scene hierarchy:

Categories