- Home /
Punching objects (C#)
Contrary to the title I mean taking an object, such as a cube or fist model, and say when you hit mouse button 1 the fist or cube "punches." I have been trying to figure this out for several hours and I know it should be pretty simple but I don't know what to do. Help is much appreciated, thanks!
Punch as in out and back motion. How you do it will depend on your requirements. I would be easy to do with an Animation.
Yeah out and back motion. I want to do it through script so that it is easier to control.
Answer by robertbu · Jun 29, 2014 at 05:57 AM
Here is a simple punching script. Note if you want the punch to interact with Rigidbodies, it would be best to rewrite the manipulation of the transform to use Rigidbody.MovePosition().
#pragma strict
var punching = false;
function Update() {
if (!punching && Input.GetKeyDown(KeyCode.Space)) {
Punch(0.5, 1.25, transform.forward);
}
}
function Punch(time : float, distance : float, direction : Vector3 ) {
punching = true;
var timer = 0.0;
var orgPos = transform.position;
direction.Normalize();
while (timer <= time) {
transform.position = orgPos + (Mathf.Sin(timer / time * Mathf.PI) + 1.0) * direction;
yield;
timer += Time.deltaTime;
}
transform.position = orgPos;
punching = false;
}
using UnityEngine;
using System.Collections;
public class Punching : $$anonymous$$onoBehaviour {
private bool punching = false;
void Update() {
if (!punching && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)) {
StartCoroutine(Punch(0.5f, 1.25f, transform.forward));
}
}
IEnumerator Punch(float time, float distance, Vector3 direction) {
punching = true;
var timer = 0.0f;
var orgPos = transform.position;
direction.Normalize();
Debug.Log("Above the loop");
while (timer <= time) {
Debug.Log("----");
transform.position = orgPos + ($$anonymous$$athf.Sin(timer / time * $$anonymous$$athf.PI) + 1.0f) * direction;
yield return null;
timer += Time.deltaTime;
}
transform.position = orgPos;
punching = false;
}
}
Your answer
Follow this Question
Related Questions
Using Lerp in a Constant Moving Object 1 Answer
Distribute terrain in zones 3 Answers
Rigidody.velocity = Direction * speed; How to get direction? 1 Answer
Multiple Cars not working 1 Answer
Reflect bullets in 3D world space 1 Answer