Rotate Object Smoothly - c#

i am trying to rotate object to 90 degrees smoothly on swipe here in my code its rotate instantly, how do i rotate object smoothly at given speed.
void Update()
{
if (fingerDown == false && Input.GetMouseButtonDown(0))
{
startPos = Input.mousePosition;
fingerDown = true;
}
if (fingerDown)
{
if (Input.mousePosition.x >= startPos.x + pixelDistToMove)
{
startPos = Input.mousePosition;
Vector3 rotationToAdd = new Vector3(0, 0, 90);
transform.Rotate(rotationToAdd);
fingerDown = false;
}
if (Input.mousePosition.x <= startPos.x - pixelDistToMove)
{
startPos = Input.mousePosition;
Vector3 rotationToAdd = new Vector3(0, 0, -90);
transform.Rotate(rotationToAdd);
fingerDown = false;
}
}
if (fingerDown && Input.GetMouseButtonUp(0))
{
fingerDown = false;
}
}
Thank you

transform.Rotate() rotates the object without animating it's rotation.
If you want it to rotate smoothly, you have to implement either an animation, or a turning state, or an IEnumerator.
My C# is a bit rusty, but I cooked this up:
public Vector3 desired_angle = Vector3.zero; // Turn the Gameobject to this angle
public float turn_time = 1f; // How long should turning take
public float rate = 60;
private void Update ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(TurnTo());
}
}
IEnumerator TurnTo ()
{
Vector3 original_angle = transform.rotation.eulerAngles;
for (float i = 0f; i < 1f + turn_time / rate; i += turn_time / rate)
{
transform.rotation = Quaternion.Euler(Vector3.Lerp(original_angle, desired_angle, i));
yield return new WaitForSeconds(turn_time/rate);
}
}

Related

Trying to making a ledge. The problem: transform.position always returns to vector( 0, 0)

I'm trying to make a method that lets players climb a ledge. I have two raycast one for Ledge and one for Wall detection. I the ledge is false, then climb the ledge.
Here comes the problem:
When the Wall check is true and the ledge Check is true, Set player transform.position to be near the ledge. Then afterward transform.position to be above the ledge. But for some reason whenever I try to call Set player transform.position near the ledge, it just teleports back to the default vector value 0, 0.
[Header("Ledge check")]
private bool canClimbLedge = false;
private bool ledgeDetected;
private Vector2 workspace;
//NEW SHIT
private Vector2 detectedPos;
private Vector2 cornerPos;
private Vector2 startPos;
private Vector2 stopPos;
[Header("Ledge Climb State")]
public Vector2 startOffset;
public Vector2 stopOffset;
private void FixedUpdate()
{ if (coll.isTouchingWall && !coll.isTouchingRightLedge || !coll.isTouchingLeftLedge)
{
SetDetectedPosition(transform.position);
}
}
void Update()
{
DetermineCornerPosition();
if (coll.onWall && !coll.isTouchingRightLedge)
CheckLedgeClimb();
if(canClimbLedge && coll.onGround)
FinishLedgeClimb();
if (dir.x < 0)
{
if (groundTouch == true && !wallGrab)
// dustParticle.Play();
if (wallGrab != true)
{
side = -1;
//anim.Flip(side);
}
}
if (dir.x > 0)
{
if (groundTouch == true && !wallGrab)
// dustParticle.Play();
if (wallGrab != true)
{
side = 1;
// anim.Flip(side);
}
}
}
public void SetDetectedPosition(Vector2 pos) => detectedPos = pos;
public Vector2 DetermineCornerPosition()
{
RaycastHit2D xHit = Physics2D.Raycast(coll.wallCheck.position, Vector2.right * side, coll.wallCheckDistance, coll.groundLayer);
float xDist = xHit.distance;
workspace.Set((xDist * side) * side, 0.015f);
RaycastHit2D yHit = Physics2D.Raycast(coll.ledgeCheck.position + (Vector3)(workspace), Vector2.down, coll.ledgeCheck.position.y - coll.wallCheck.position.y + 0.015f, coll.groundLayer);
float yDist = yHit.distance;
//Upper Corner Position of ledge
workspace.Set(coll.wallCheck.position.x + (xDist * side), coll.ledgeCheck.position.y - yDist);
return workspace;
}
private void CheckLedgeClimb()
{
if (coll.isTouchingWall && !coll.isTouchingRightLedge && !ledgeDetected)
{
ledgeDetected = true;
//Freeze player in the detectedPos
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;
transform.position = detectedPos;
cornerPos = DetermineCornerPosition();
}
if(ledgeDetected && !canClimbLedge)
{
canClimbLedge = true;
startPos.Set(cornerPos.x - (side * startOffset.x), cornerPos.y - startOffset.y);
stopPos.Set(cornerPos.x + (side * stopOffset.x), cornerPos.y + stopOffset.y);
}
Debug.Log(startPos);
canMove = false;
transform.position = startPos;
canClimbLedge = true;
}
public void FinishLedgeClimb()
{
//Call the last part of climbing the ledge
}
In the Collision Script:
void FixedUpdate()
{
isTouchingWall = Physics2D.Raycast(wallCheck.position, transform.right, wallCheckDistance, groundLayer);
isTouchingRightLedge = isTouchingWall = Physics2D.Raycast(ledgeCheck.position, transform.right, wallCheckDistance, groundLayer);
}
Any help will be much appreciated, and if you have any other solution to make a ledge climber, I'm all ears.
I reevaluated the purpose was with the script.
The problem was Raycast was not really working correctly
And instead of making the raycast shoot in one direction, I made it follow change 180 degrees if the player was facing left.
And in my game, I didn't want the player to be able to hang from a ledge so the transform.position was removed.
Changes:
Collision Script:
isTouchingWall = Physics2D.Raycast(wallCheck.position, transform.right * move.side, wallCheckDistance, groundLayer);
isTouchingLedge = Physics2D.Raycast(ledgeCheck.position, transform.right * move.side, wallCheckDistance, groundLayer);
ClimbLedge Function:
private void CheckLedgeClimb()
{
if (coll.isTouchingWall && !coll.isTouchingLedge && !ledgeDetected)
{
//Reference point to startPos and stopPos
ledgeDetected = true;
//Freeze player in the detectedPos
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;
transform.position = detectedPos;
cornerPos = DetermineCornerPosition();
Debug.Log("cornerPos Vector Value: " + cornerPos);
canClimbLedge = false;
}
if(ledgeDetected && !canClimbLedge)
{
//This part is only necessary if you want the player to hang from a ledge.
/*startPos.Set(cornerPos.x - (side * startOffset.x), cornerPos.y - startOffset.y);
stopPos.Set(cornerPos.x + (side * stopOffset.x), cornerPos.y + stopOffset.y);
Debug.Log("startPos when ledgeDetected + !canClimbLedge:" + startPos);
canMove = false;
transform.position = startPos;
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;*/
stopPos.Set(cornerPos.x + (side * stopOffset.x), cornerPos.y + stopOffset.y);
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;
canMove = false;
canClimbLedge = true;
}
}
public void FinishLedgeClimb()
{
if (canClimbLedge)
{
transform.position = stopPos;
canClimbLedge = false;
canMove = true;
ledgeDetected = false;
Debug.Log("transform.position = stopPos");
//anim.SetBool("canClimbLedge", canClimbLedge);
}
}
This is working, but the timing of when the player transform.position to the stopPos, is sometimes delayed.

Player Movement using joystick based on camera facing

I am developing an offline FPS multiplayer game.
When the Player Rotation value is (0,0,0), then Player moves perfectly in direction. However, my problem is when I rotate the camera using touch input. The player can also rotate his face and press the joystick button for moving the player, but then the player should not move the direction the camera is facing.
My Joystick Script For Player
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler,IPointerDownHandler {
private Image bgImg;
private Image JoyStickImage;
private Vector3 InputVector;
private void Start(){
bgImg = GetComponent<Image> ();
JoyStickImage = transform.GetChild (0).GetComponent<Image> ();
}
public virtual void OnDrag(PointerEventData ped){
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle (bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos)) {
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);
InputVector = new Vector3 (pos.x * 2 + 1, 0, pos.y * 2 - 1);
InputVector = (InputVector.magnitude > 1) ? InputVector.normalized : InputVector;
JoyStickImage.rectTransform.anchoredPosition = new Vector3 (InputVector.x * (bgImg.rectTransform.sizeDelta.x / 2.5f),
InputVector.z * (bgImg.rectTransform.sizeDelta.y / 2.5f));
}
}
public virtual void OnPointerDown(PointerEventData ped){
OnDrag (ped);
}
public virtual void OnPointerUp(PointerEventData ped){
InputVector = Vector3.zero;
JoyStickImage.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal(){
if (InputVector.x != 0) {
return InputVector.x;
} else {
return Input.GetAxis ("Horizontal");
}
}
public float Vertical(){
if (InputVector.z != 0)
return InputVector.z;
else
return Input.GetAxis ("Vertical");
}
}
My Camera Rotation Script Using Input Touch
public class SwipeCam : MonoBehaviour {
private Vector3 firstPoint;
private Vector3 secondPoint;
private float xAngle = 0.0f;
private float yAngle = 0.0f;
private float xAngleTemp = 0.0f;
private float yAngleTemp = 0.0f;
void Start(){
xAngle = 0.0f;
yAngle = 0.0f;
this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);
}
void Update() {
if (Input.touchCount > 0) {
for (int i = 0; i < Input.touchCount; i++) {
Touch touch = Input.GetTouch (i);
if (touch.position.x > Screen.width / 2) {
if (touch.phase == TouchPhase.Began) {
firstPoint = Input.GetTouch (0).position;
xAngleTemp = xAngle;
yAngleTemp = yAngle;
}
if (touch.phase == TouchPhase.Moved) {
secondPoint = Input.GetTouch (0).position;
xAngle = xAngleTemp + (secondPoint.x - firstPoint.x) * 180.0f / Screen.width;
yAngle = yAngleTemp + (secondPoint.y - firstPoint.y) * 180.0f / -Screen.height;
yAngle = Mathf.Clamp (yAngle, -30f, 30f);
this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);
this.gameObject.GetComponentInParent<FPScontroller> ().transform.rotation = Quaternion.Euler (0.0f, xAngle, 0.0f);
//this.gameObject.GetComponentInParent<FPScontroller> ().transform.rotation = Quaternion.LookRotation(Vector3.forward,Vector3.up);
}
}
}
}
}
}
Where should I change my code to fix the facing the camera direction to player issue.
That is my Player Script (FPSController.cs)
public class FPScontroller : MonoBehaviour {
// Should this script respond to input?
public bool canControl = true;
public GameObject lookObj; //This is root object that containc MainCamera, Weapons etc.
public GameObject joystick;
bool useFixedUpdate = false;
//Check when run, walk or when can run or not
[HideInInspector]
public bool Running ;
[HideInInspector]
public bool Walking;
[HideInInspector]
public bool canRun;
[HideInInspector]
public Vector3 rorationDir;
//Ladder variables
private GameObject mainCamera = null;
[HideInInspector]
public bool onLadder = false;
//private float ladderHopSpeed = 6.0f;
// For the next variables, #System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The current global direction we want the character to move in.
[System.NonSerialized]
public Vector3 inputMoveDirection = Vector3.zero;
// Is the jump button held down? We use this interface instead of checking
// for the jump button directly so this script can also be used by AIs.
[System.NonSerialized]
public bool inputJump = false;
[HideInInspector]
public bool inputRun = false;
[HideInInspector]
public bool inputCrouch = false;
[HideInInspector]
public bool inputProne = false;
[System.Serializable]
public class FPScontrollerMovement {
// The maximum horizontal speed when moving
[HideInInspector]
public float maxForwardSpeed = 10.0f;
[HideInInspector]
public float maxSidewaysSpeed = 10.0f;
[HideInInspector]
public float maxBackwardsSpeed = 10.0f;
//Run and walk variables
public float WalkSpeed = 6.0f;
public float RunSpeed = 9.0f;
//Crouch
public bool canCrouch = true;
public float CrouchSpeed = 3.0f;
public float crouchHeight = 1.5f;
public float crouchSmooth = 8;
//prone
public bool canProne = true;
public float ProneSpeed = 1.5f;
public float proneHeight = 0.7f;
// Curve for multiplying speed based on slope (negative = downwards)
public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0));
// How fast does the character change speeds? Higher is faster.
public float maxGroundAcceleration = 30.0f;
public float maxAirAcceleration = 20.0f;
// The gravity for the character
public float gravity = 10.0f;
public float maxFallSpeed = 20.0f;
[HideInInspector]
public bool enableGravity = true;
// For the next variables, #System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The last collision flags returned from controller.Move
[System.NonSerialized]
public CollisionFlags collisionFlags;
// We will keep track of the character's current velocity,
[System.NonSerialized]
public Vector3 velocity;
// This keeps track of our current velocity while we're not grounded
[System.NonSerialized]
public Vector3 frameVelocity = Vector3.zero;
[System.NonSerialized]
public Vector3 hitPoint = Vector3.zero;
[System.NonSerialized]
public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0);
}
public FPScontrollerMovement movement = new FPScontrollerMovement();
void Awake () {
if (GetComponent<NetworkView> ().isMine) {
joystick = GameObject.Find ("Joystick");
controller = gameObject.GetComponent<CharacterController>();
standartHeight = controller.height;
/*if(GameObject.FindWithTag("LookObject") != null){
lookObj = GameObject.FindWithTag("LookObject");
}*/
centerY = controller.center.y;
tr = transform;
canRun = true;
canStand = true;
StartCoroutine(setupBools());
}
}
void Update () {
if (GetComponent<NetworkView> ().isMine) {
if (!useFixedUpdate) {
UpdateFunction ();
}
movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;
//Run input
if (Input.GetAxis ("Vertical") > 0.1f && inputRun && canRun && !onLadder && Walking) {
if (canStand && canStandCrouch) {
OnRunning ();
}
} else {
OffRunning ();
}
//Check when walk or not
if ((movement.velocity.x > 0.01f || movement.velocity.z > 0.01f) || (movement.velocity.x < -0.01f || movement.velocity.z < -0.01f)) {
RunAnimation1 ();
Debug.Log ("Forward");
Walking = true;
}else if (movement.velocity.x > 0.01f) {
Walking = true;
Debug.Log ("Right");
} else if (movement.velocity.x < -0.01f) {
Walking = true;
Debug.Log ("Left");
} else {
RunAnimation ();
Walking = false;
}
if (!canControl)
return;
if (movement.canCrouch) {
if (!onLadder) {
Crouch ();
}
}
if (movement.canProne) {
if (!onLadder) {
Prone ();
}
}
if (onLadder) {
grounded = false;
crouch = false;
prone = false;
}
if (!crouch && !prone && controller.height < standartHeight - 0.01f) {
controller.height = Mathf.Lerp (controller.height, standartHeight, Time.deltaTime / movement.crouchSmooth);
controller.center = new Vector3 (controller.center.x, Mathf.Lerp (controller.center.y, centerY, Time.deltaTime / movement.crouchSmooth), controller.center.z);
lookObj.transform.localPosition = new Vector3 (lookObj.transform.localPosition.x, Mathf.Lerp (lookObj.transform.localPosition.y, standartHeight, Time.deltaTime / movement.crouchSmooth), lookObj.transform.localPosition.z);
}
}
}
void RunAnimation(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 0);
}
void RunAnimation1(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 1);
}
void RunAnimation2(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 2);
}
[RPC]
void SysnAnimation(int index){
if (index == 0) {
GetComponent<Animator> ().Play ("Idle Aim");
} else if (index == 1) {
GetComponent<Animator> ().Play ("Walk Aiming");
} else if (index == 2) {
GetComponent<Animator> ().Play ("Jump");
}
}
void OnRunning (){
Debug.Log ("Run");
Running = true;
movement.maxForwardSpeed = movement.RunSpeed;
movement.maxSidewaysSpeed = movement.RunSpeed;
//Make bigger extra height when player run to increase jump distance
jumping.extraHeight = jumping.baseHeight + 0.15f;
}
void OffRunning (){
Running = false;
if(crouch || prone)
return;
movement.maxForwardSpeed = movement.WalkSpeed;
movement.maxSidewaysSpeed = movement.WalkSpeed;
movement.maxBackwardsSpeed = movement.WalkSpeed/2;
//Change extraheight value to default when player walk
jumping.extraHeight = jumping.baseHeight;
}}
Your camera and joystick code looks fine, but that's not where the problem is.
I'll assume your player movement code looks something like this:
Get input X and Y
Move player right by X, forward by Y
In code form, that might look something like this:
//returns the world-space direction that player wants to move
Vector3 GetDesiredMovement(float inputForward, float inputRight) {
//get a vector pointing to player's right
Vector3 dirRight = Camera.main.transform.right;
dirRight.y = 0f;
dirRight.Normalize();
//get a vector pointing to player's front
Vector3 dirForward = Camera.main.transform.forward;
dirForward.y = 0f;
dirForward.Normalize();
//calculate desired movement based on input
Vector3 desiredMovement = (dirForward * inputForward) + (dirRight * inputRight);
desiredMovement.Normalize();
return desiredMovement;
}
What if "right" and "forward" need to be relative to some other object in the scene, such as a camera? It's easier than you might think: just read those values directly from the camera's transform component.
You could do that by replacing just two lines from the above example:
Vector3 dirRight = Camera.main.transform.right;
Vector3 dirForward = Camera.main.transform.forward;
I solved the problem of basing player movement of the camera's direction.
In my Player's script there are two lines that read joystick input:
movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;`
I changed them to this:
Vector3 DirectionVector =
new Vector3 (joystick.GetComponent<VirtualJoystick> ().Horizontal (), 0f, joystick.GetComponent<VirtualJoystick> ().Vertical ());
movement.velocity = transform.rotation * DirectionVector * 10f;
Directly add joystick value in movement vector. I just multiply it to the joystick input vector and solve my problem.
Now the player moves based on the player rotation and where the camera is facing.
Thanks everyone for help.

Raycasting unknown error

I have this problem which I have been trying to figure out for quite some time already. The code I have below is almost complete. I just need to add this additional feature it should work how I want it to work.
So what I want to implement into the code is the make alertedLock false when !withinRange.
But for some reason no matter how i do it. It doesnt work. Because the problem i have is that, when i implement some kind of code to do that, everything goes back to normal.
Thanks in advance.
Edit
The script should be doing this:
If player !withinRange && !withinAngle of enemy then, enemy.color.blue;
If player !withinRange && withinAngle of enemy then, enemy.color.blue;
If player withinRange && !withinAngle of enemy then, enemy.color.red;
If player withinRange && withinAngle of enemy then, enemy.color.green;
If player withinRange && touchRestrictedRaycast of enemy then, enemy.color.magenta (forever) unless !withinRange && !withinAnge
The problem is 5. I dont know how to code 5.
Edit
When i tried to code it outside the forloop , that is,
if (alertedLock && !withinRange) {
alertedLock = false;
}
Does doesnt solve the problem. It returns the solution to where alertedLock is always false
Even when i try to apply it inside the for loop. Such like,
if(withinRange) {
// Inside
if(alertedLock) {
gameObject.renderer.material.color = Color.magenta;
}
if(!alertedLock) {
if(enemyAngleTLUP || enemyAngleTLLEFT) {
alertedLock = true;
}
if(withinAngle) {
gameObject.renderer.material.color = Color.green;
}
if(!withinAngle) {
gameObject.renderer.material.color = Color.red;
}
}
}
if (!withinRange){
if(alteredLock) {
alertedLock = false;
}
}
There is a problem when i do this, its because once it detects the first raycast detection. It ignores the rest, and so it has this color state problem.
I found out this problem on my earlier questions, here:
https://gamedev.stackexchange.com/questions/90329/raycast-flashing-problem
Edit
alertedLock is just a bool which determines when the player has touched the restricted raycast. Due to the fact the player can only kill the enemy from a certain range and angle (withinRange && withinAngle). This is why we have alertedLock.
However, when alertedLock is true. It can only be turned off when the player isnt within the kill range of the enemy (!withinRange)
using UnityEngine;
using System.Collections;
public class Script_v2 : MonoBehaviour {
// Player Properties
private GameObject player;
public Vector3 playerSize;
private Vector3 playerTransform;
public Vector3 playerTransformTL;
public Vector3 playerTransformTR;
public Vector3 playerTransformBL;
public Vector3 playerTransformBR;
private Vector3 newPlayerTransformTL;
private Vector3 newPlayerTransformTR;
private Vector3[] playerRaycastPoints;
// Enemy Properties
private Vector3 enemyTransformTL;
private Vector3 enemyTransformTR;
private Vector3 enemyTransformBL;
private Vector3 enemyTransformBR;
public float distance;
public Vector3 enemySize;
// Detection Alerts
public bool outOfVision;
public bool alerted;
public bool alertedLock;
public bool withinRange;
public bool withinAngle;
public bool dead;
Ray ray;
RaycastHit hit;
// Use this for initialization
void Start () {
playerRaycastPoints = new Vector3[4];
distance = 3f;
player = GameObject.FindGameObjectWithTag ("Player");
}
// Update is called once per frame
void Update () {
enemyTransformTL = new Vector3 (transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z);
enemyTransformTR = new Vector3 (transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z);
enemyTransform_TL_TR ();
Reference_Player_Transform_Points ();
Player_Transform_Points_Detection ();
Debug.Log (alerted + " " + alertedLock);
}
void OnDrawGizmos() {
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere (new Vector3(transform.position.x - 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
//Gizmos.DrawWireSphere (new Vector3(transform.position.x + 0.5f, transform.position.y + 0.5f, transform.position.z), distance);
}
public void enemyTransform_TL_TR() {
if (alertedLock && !withinRange) {
alertedLock = false;
}
if (!alertedLock) {
gameObject.renderer.material.color = Color.blue;
}
for (int i = 0; i < playerRaycastPoints.Length; i++) {
double enemyAngleTL = Mathf.Atan2(playerRaycastPoints[i].y - ( transform.position.y + 0.5f ),
playerRaycastPoints[i].x - ( transform.position.x - 0.5f )) * 180f / 3.14159265f;
//Debug.Log (enemyAngleTL);
double enemyAngleTR = Mathf.Atan2 (playerRaycastPoints[i].y - (transform.position.y + 0.5f),
playerRaycastPoints[i].x - (transform.position.x + 0.5f)) * 180f / 3.14159265f;
Vector3 directionTL = (playerRaycastPoints[i] - enemyTransformTL).normalized;
Ray rayTL = new Ray(enemyTransformTL, directionTL);
RaycastHit hitTL;
Vector3 directionTR = (playerRaycastPoints[i] - enemyTransformTR).normalized;
Ray rayTR = new Ray (enemyTransformTR, directionTR);
RaycastHit hitTR;
withinRange = Physics.Raycast (rayTL, out hitTL, distance);
withinAngle = enemyAngleTL > 90 && enemyAngleTL < 180;
RaycastHit hitTPUP;
RaycastHit hitTPLEFT;
bool enemyAngleTLUP = Physics.Raycast(enemyTransformTL, Vector3.up, out hitTPUP, distance);
bool enemyAngleTLLEFT = Physics.Raycast(enemyTransformTL, Vector3.left, out hitTPLEFT, distance);
Debug.DrawRay(enemyTransformTL, Vector3.up * distance);
Debug.DrawRay(enemyTransformTL, Vector3.left * distance);
if(withinRange) {
// Inside
if(alertedLock) {
gameObject.renderer.material.color = Color.magenta;
}
if(!alertedLock) {
if(enemyAngleTLUP || enemyAngleTLLEFT) {
alertedLock = true;
}
if(withinAngle) {
gameObject.renderer.material.color = Color.green;
}
if(!withinAngle) {
gameObject.renderer.material.color = Color.red;
}
}
}
}
}
private void Reference_Player_Transform_Points() {
playerSize = player.transform.localScale;
playerTransformTL = new Vector3(player.transform.position.x - (playerSize.x / 2),
player.transform.position.y + playerSize.y / 2,
player.transform.position.z);
playerTransformTR = new Vector3(player.transform.position.x + (playerSize.x / 2),
player.transform.position.y + playerSize.y / 2,
player.transform.position.z);
playerTransformBL = new Vector3(player.transform.position.x - (playerSize.x / 2),
player.transform.position.y - playerSize.y / 2,
player.transform.position.z);
playerTransformBR = new Vector3(player.transform.position.x + (playerSize.x / 2),
player.transform.position.y - playerSize.y / 2,
player.transform.position.z);
playerRaycastPoints [0] = playerTransformTL;
playerRaycastPoints [1] = playerTransformTR;
playerRaycastPoints [2] = playerTransformBL;
playerRaycastPoints [3] = playerTransformBR;
/*
Debug.Log (playerTransformTL);
Debug.Log (playerTransformTR);
Debug.Log (playerTransformBL);
Debug.Log (playerTransformBR);
*/
}
private void Player_Transform_Points_Detection() {
float eTLpTL = Vector3.Distance (enemyTransformTL, playerTransformTL);
float eTLpTR = Vector3.Distance (enemyTransformTL, playerTransformTR);
float eTLpBL = Vector3.Distance (enemyTransformTL, playerTransformBL);
float eTLpBR = Vector3.Distance (enemyTransformTL, playerTransformBR);
float eTRpTL = Vector3.Distance (enemyTransformTR, playerTransformTL);
float eTRpTR = Vector3.Distance (enemyTransformTR, playerTransformTR);
float eTRpBL = Vector3.Distance (enemyTransformTR, playerTransformBL);
float eTRpBR = Vector3.Distance (enemyTransformTR, playerTransformBR);
float eTLMin = Mathf.Min (eTLpTL, eTLpTR, eTLpBL, eTLpBR);
if (eTLMin == eTLpTL) {
newPlayerTransformTL = playerTransformTL;
// Debug.Log("eTLpTL");
}
else if(eTLMin == eTLpTR) {
newPlayerTransformTL = playerTransformTR;
// Debug.Log("eTLpTR");
}
else if(eTLMin == eTLpBL) {
newPlayerTransformTL = playerTransformBL;
// Debug.Log("eTLpBL");
}
else if(eTLMin == eTLpBR) {
newPlayerTransformTL = playerTransformBR;
// Debug.Log("eTLpBR");
}
float eTRMin = Mathf.Min (eTRpTL, eTRpTR, eTRpBL, eTRpBR);
if(eTRMin == eTRpTL) {
newPlayerTransformTR = playerTransformTL;
// Debug.Log("eTRpTL");
}
else if(eTRMin == eTRpTR) {
newPlayerTransformTR = playerTransformTR;
// Debug.Log("eTRpTR");
}
else if(eTRMin == eTRpBL) {
newPlayerTransformTR = playerTransformBL;
// Debug.Log("eTRpBL");
}
else if(eTRMin == eTRpBR) {
newPlayerTransformTR = playerTransformBR;
// Debug.Log("eTRpBR");
}
}
}

Moving object along a raycast in unity using c#

I want to move an object along a ray gradually,
I have the following code so far which moves it in 1 frame to the destination rather than smoothly gliding there.
If I remove the Destroy(projectile.rigidbody2D) line from the end it sort of does it but then bounces around all over the place?
Any help would be much appreciated!
void Update ()
{
if (Input.GetMouseButtonUp (1)) {
if (Hand.transform.childCount == 1){
projectile.gameObject.transform.parent = null;
Ray ray = new Ray(spawn.position,spawn.up);
RaycastHit hit;
float shotDistance = shotdistance;
if (Physics.Raycast(ray,out hit, shotDistance)) {
shotDistance = hit.distance;
}
projectile.AddComponent<Rigidbody2D>();
projectile.rigidbody2D.gravityScale = 0;
projectile.rigidbody2D.AddForce(Vector2.up * 5);
projectile.transform.position = Vector3.MoveTowards(projectile.transform.position,ray.direction * shotDistance,shotDistance);
Debug.DrawRay(ray.origin,ray.direction * shotDistance,Color.red,1);
Destroy(projectile.rigidbody2D);
}
}
}
private float lerpValue = 0;
public float speed;
private Vector3 startPosition;
private bool isMoving;
void Update ()
{
if (Input.GetMouseButtonUp (1))
{
if (Hand.transform.childCount == 1)
{
lerpValue = 0;
startPosition = projectile.transform.position;
projectile.gameObject.transform.parent = null;
Ray ray = new Ray(spawn.position,spawn.up);
RaycastHit hit;
float shotDistance = shotdistance;
if (Physics.Raycast(ray,out hit, shotDistance) && !isMoving)
{
isMoving = true;
shotDistance = hit.distance;
//speed = distance / time
//therefore: time = distance / speed
float time = shotDistance / speed;
StartCoroutine(ProjectileMotion(hit.point, time));
}
}
}
}
IEnumerator ProjectileMotion(Vector3 endPosition, float time)
{
while(lerpValue < time)
{
lerpValue += Time.deltaTime;
projectile.transform.position = Vector3.Lerp(startPosition, endPosition, lerpValue / time);
}
isMoving = false;
}

XNA enemy wandering

Can anyone help me. I want my sprite to only move left and right / up and down. Then if the player goes near the enemy in a specific range of X / Y the enemy would follow the Player until the Player escape in a specific range. ( this code can only follow the player in the X coordinate )
class Enemy
{
Texture2D enemy_Texture;
Vector2 enemy_Position;
Vector2 enemy_Origin;
Vector2 enemy_Velocity;
Rectangle enemy_Rectangle;
float enemy_Rotation = 0f;
float enemy_DistanceFromPlayer;
float enemy_OldDistanceFromPlayer;
bool right = true;
public Enemy(Texture2D texture, Vector2 position, float distance)
{
enemy_Texture = texture;
enemy_Position = position;
enemy_DistanceFromPlayer = distance;
enemy_OldDistanceFromPlayer = enemy_DistanceFromPlayer;
}
float player_Position;
public void Update(Player player)
{
enemy_Position += enemy_Velocity;
enemy_Origin = new Vector2(enemy_Texture.Width / 2, enemy_Texture.Height / 2);
player_Position = player.X - enemy_Position.X;
if (player_position<enemy_DistanceFromPlayer)
{
enemy_Position += new Vector2(1, 0);
}
if (player_position > enemy_DistanceFromPlayer)
{
enemy_Position += new Vector2(-1, 0);
}
/*
if (enemy_DistanceFromPlayer <= enemy_OldDistanceFromPlayer)
{
right = true;
enemy_Velocity.X = 1f;
}
else if (enemy_DistanceFromPlayer >= enemy_OldDistanceFromPlayer)
{
right = false;
enemy_Velocity.X = -1f;
}
//if (right) enemy_DistanceFromPlayer += 1; enemy_DistanceFromPlayer -= 1;
if (player_Position >= -20 && player_Position <= 20)
{
if (player_Position < -1)
{
enemy_Velocity.X = 1f;
}
else if (player_Position > 1)
{
enemy_Velocity.X = -1f;
}
else if (player_Position == 0)
{
enemy_Velocity.X = 0f;
}
}*/
}
public void Draw(SpriteBatch spritebatch)
{
if (enemy_Velocity.X > 0)
{
spritebatch.Draw(enemy_Texture, enemy_Position, null, Color.Wheat, enemy_Rotation, enemy_Origin, 1f,SpriteEffects.FlipHorizontally, 0f);
}
else
{
spritebatch.Draw(enemy_Texture, enemy_Position, null, Color.Wheat, enemy_Rotation, enemy_Origin, 1f, SpriteEffects.None, 0f);
}
}
}
An easier way would be to just go by distance instead of handling X/Y independently. Define a chase_threshold somewhere like a class-level field.
const float chase_threshold = 4f; // Chase player if less than 4 squares away
Then this could be your chase logic:
float distance = Vector2.Distance(player, enemy);
if (distance < chase_threshold)
{
Vector2 direction;
// Should we go left/right or up/down?
if (Math.Abs(player.X - enemy_Position.X) > Math.Abs(player.Y - enemy_Position.Y)
direction = new Vector2(player.X - enemy_Position.X, 0);
else
direction = new Vector2(0, player.Y - enemy_Position.Y);
enemy_Position += direction * enemy_Velocity;
}
This is now a working Code, but the sprite keeps following me. I wanted to know how to make it stop.
class Enemy
{
Texture2D enemy_Texture;
Vector2 enemy_Position;
Vector2 enemy_Origin;
Vector2 enemy_Velocity;
Rectangle enemy_Rectangle;
float enemy_Rotation = 0f;
float enemy_DistanceFromPlayer;
float enemy_OldDistanceFromPlayer;
bool right = true;
public Enemy(Texture2D texture, Vector2 position, float distance)
{
enemy_Texture = texture;
enemy_Position = position;
enemy_DistanceFromPlayer = distance;
enemy_OldDistanceFromPlayer = enemy_DistanceFromPlayer;
}
Vector2 player_Position;
Vector2 distanceFromTarget;
float rangeToMove = 4f; // this is the range where the enemy will start to move, if the player get near it
float distanceFromPlayer;
public void Update(Player player, GameTime gameTime)
{
player_Position = new Vector2(player.X, player.Y);
distanceFromTarget = player_Position - enemy_Position;
distanceFromPlayer = Vector2.Distance(player_Position, enemy_Position);
distanceFromTarget.Normalize();
if (rangeToMove<distanceFromPlayer)
{
enemy_Position += distanceFromTarget * (float)gameTime.ElapsedGameTime.TotalMilliseconds * .1f;
}
}
I'm assuming your .1f; is referring to the speed your enemy is chasing the player at.
If so, if you add in a speed variable where your .1f is for your enemy.
Try adding to your
float speed;
if (rangeToMove<distanceFromPlayer)
{
enemy_Position += distanceFromTarget * (float)gameTime.ElapsedGameTime.TotalMilliseconds * speed;
}
else
{
speed = 0.0f;
}

Categories